By Sam Deering

jQuery .val() works 2 ways on select inputs

By Sam Deering
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

Quicky. It might be handy if you didn’t know that .val() function works 2 ways on select boxes to set the value of the drop down.



Way 1

$('select').val('1'); // selects "Two"

Way 2

$('select').val('Two'); // also selects "Two"

Other methods

$("#my-Select option[text='Option1']").attr("selected","selected");

$('#my-Select option[value="1"]').attr("selected","selected") ; or $('#my-Select option:nth(2)').attr("selected","selected");

Also see: jQuery Loop Select Options

Login or Create Account to Comment
Login Create Account
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?