tags:

views:

43

answers:

2

I have one slect box with various options.

I want that when page loads then one option with value e,g 10 should be preselected with jquery

how can i do that

thanks

+4  A: 

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>​
patrick dw
+1 Correct of course! I might add that with `.val()` you supply the value between the `<option></option>` tags, not the `value=` attribute. So in the case of `<option value="10">Ten</option>` you would use `$("#mySelectBox").val('Ten')`
Doug Neiner
@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/
patrick dw
@patrick Dude.. seriously? I always thought that method was #fail... I need to read the source more. Thanks!
Doug Neiner
@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)
patrick dw
+3  A: 

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

$("option[value='10']").attr('selected','selected');
Adam
You'll need to remove the descendant operator (space) from the selector for it to work. :o)
patrick dw
@patrick Thanks. I corrected it
Adam
+1 I prefer this approach more so than using `val()` to set these. I'm not even sure how `val()` is supposed to work if you are presenting a multiple-select listbox...
Funka
@Funka - If it is a multiple select, it will accept an array of values to set. *example* http://jsfiddle.net/VArCZ/2/
patrick dw