jQuery .val() works 2 ways on select inputs

By Sam Deering

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

  • Guillaume Poussel

    The method described in ‘Other methods’ actually does not work. It tries to select a tag with name ‘option1’. It should be something like:
    $('#my-Select option[value="1"]').attr("selected","selected") ; or $('#my-Select option:nth(2)').attr("selected","selected") ;

    • jquery4u


      Thanks, good spot. It seems the code display wasn’t picking up my code properly.

      It read in the src: $(“#my-Select option[text language=”Option1″][/text]”).attr(“selected”,”selected”);

      I’ve added your examples too.

Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.