1 2Geek Answers HandbookProgrammatically select an item from the drop-down list.I have a drop down menu:<select> <option value="1">1</option> <option value="2">2</option> </select> How can I select item 2 programmatically?+7htmlCrazyCoder Mar 05 '11 at 18:59source share6 answersFirst, take a handle that you choose somehow: var select = document.getElementsByTagName("SELECT")[0]; Then manipulate the selectedIndex property (I believe this is a zero-based index): select.selectedIndex = 1; +7jpsimons Mar 05 '11 at 19:04source shareIf you're talking about pre-selecting an item, just set the item as “selected” as follows: <select> <option value="1">1</option> <option value="2" selected="selected">2</option> </select> +4John parker Mar 05 '11 at 19:04source shareIf you use plain HTML: <option selected value="2">2</option> If you can use jQuery, use the val() method: <select id="foo"> //give it an id $("#foo").val("2"); +4p.campbell Mar 05 '11 at 19:05source share <select> <option value="1">1</option> <option value="2" selected>2</option> </select> +1Tom m Mar 05 '11 at 19:04source sharejQuery edition ... $('#your_select').val('2'); +1Orbit Mar 05 '11 at 19:04source shareThe simplest solution: <select> <option value="1">1</option> <option selected value="2">2</option> </select> 0Florin Frătică Mar 05 '11 at 20:17source shareMore articles:memory usage by PHP array when adding a huge numeric key - memory-managementWhat does “Artifacts” mean in a single process? - design-patternscucumber test script automation for MySQL - mysqlUnderstanding Basic Java Issues - javaEF context management - asp.net-mvcCan I set the maximum number of rows in an unbound DataGridView - c #Correct way to set goal / action for NSMenuItem in Cocoa? - cocoato have a perl debugger does not stop on the first statement - debuggingGlassFish Deploy CommandException Error - exceptionHow to resize LWJGL window? - javaAll Articles
I have a drop down menu:
<select> <option value="1">1</option> <option value="2">2</option> </select>
How can I select item 2 programmatically?
First, take a handle that you choose somehow:
var select = document.getElementsByTagName("SELECT")[0];
Then manipulate the selectedIndex property (I believe this is a zero-based index):
select.selectedIndex = 1;
If you're talking about pre-selecting an item, just set the item as “selected” as follows:
<select> <option value="1">1</option> <option value="2" selected="selected">2</option> </select>
If you use plain HTML:
<option selected value="2">2</option>
If you can use jQuery, use the val() method:
val()
<select id="foo"> //give it an id $("#foo").val("2");
<select> <option value="1">1</option> <option value="2" selected>2</option> </select>
jQuery edition ...
$('#your_select').val('2');
The simplest solution:
<select> <option value="1">1</option> <option selected value="2">2</option> </select>