Programmatically choose item in select drop down
I have a drop down:
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
How would I select item 2 program开发者_StackOverflow中文版matically?
First get a handle on that select somehow:
var select = document.getElementsByTagName("SELECT")[0];
Then manipulate the selectedIndex property (I believe it's a zero-based index):
select.selectedIndex = 1;
If you're talking about pre-selecting an item, simply set the item as "selected" as follows:
<select>
<option value="1">1</option>
<option value="2" selected="selected">2</option>
</select>
If you're using plain HTML:
<option selected value="2">2</option>
If you're able to use jQuery, use the val()
method:
<select id="foo"> //give it an id
$("#foo").val("2");
jQuery edition...
$('#your_select').val('2');
<select>
<option value="1">1</option>
<option value="2" selected>2</option>
</select>
The easiest solution is this:
<select>
<option value="1">1</option>
<option selected value="2">2</option>
</select>
精彩评论