I have option menu like this:
<form name="AddAndEdit">
<select name="list" id="personlist">
<option value="11">Person1</option>
<option value="27">Person2</option>
<option value="17">Person3</option>
<option value="10">Person4</option>
<option value="7">Person5</option>
<option value="32">Person6</option>
<option value="18">Person7</option>
<option value="29">Person8</option>
<option value="28">Person9</option>
<option value="34">Person10</option>
<option value="12">Person11</option>
<option value="19">Person12</option>
</select>
</form>
And now I want to change the selected option by using an href. For example:
<a href="javascript:void(0);"
onclick="document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected';">change</a>
But I want to select the option with value=11 (Person1)
, not Person12
.
How do I change this code?
Change
to
mySelect.value = myValue
Just do
mySelect.value = myValue
where myValue equals the value attribute of the option you want to set it to.You could also change select.options.selectedIndex DOM attribute like this:
You can use JQuery also
Here are all the tools as pure JavaScript code for handling Selectbox:
Updated - 28-Aug-2018 | Fiddler DEMO
JavaScript Code:
An array Index will start from 0. If you want value=11 (Person1), you will get it with position
getElementsByTagName('option')[10].selected
.