16

I have one select box with various options.

When a page loads then one option with a value, for example 10, should be preselected with jQuery.

How can I do that?

Metafaniel
  • 29,318
  • 8
  • 40
  • 67

4 Answers4

27

When the page loads run this (you can put it in <body onload="//put code here">):

$("option[value='10']").attr('selected','selected');
Adam
  • 43,763
  • 16
  • 104
  • 144
23

Test the example: http://jsfiddle.net/VArCZ/

$(document).ready(function() {

    $('#mySelectBox').val('10');

});

Although, jQuery wouldn't be required for this if the intial value will be static:

<select id='mySelectBox'>
    <option value='5'>5</option>
    <option value='10' selected='selected'>10</option>
    <option value='15'>15</option>
</select>​
user113716
  • 318,772
  • 63
  • 451
  • 440
  • 3
    +1 Correct of course! I might add that with `.val()` you supply the value between the `` tags, not the `value=` attribute. So in the case of `` you would use `$("#mySelectBox").val('Ten')` – Doug Neiner Jun 24 '10 at 00:47
  • 1
    @Doug - Actually, if there is a value attribute present, it matches against that first. If no value attribute, then it tries to match against the text content. But thanks for the +1. :o) *updated example:* http://jsfiddle.net/VArCZ/1/ – user113716 Jun 24 '10 at 00:51
  • Dude.. seriously? I always thought that method was #fail... I need to read the source more. Thanks! – Doug Neiner Jun 24 '10 at 02:01
  • 1
    @Doug - Full disclosure: I had to do a quick scramble to make sure I had it right. Happens more often than I care to admit. :o) – user113716 Jun 24 '10 at 02:07
1

In the latest jQuery version this works for me:

$("option[value='10']").prop('selected',true);
Kevin Lieser
  • 951
  • 1
  • 9
  • 25
0

Above code is working you can use following code:

$("option[value='10']").attr('selected','selected');
Taryn
  • 242,637
  • 56
  • 362
  • 405
purab
  • 211
  • 1
  • 3
  • 9