I have an HTML <select>
element 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>
I want to select an option by value (e.g., value="11"
for Person1) using JavaScript when a link is clicked. I tried this code:
<a href="javascript:void(0);"
onclick="document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected';">change</a>
But it selects Person12
instead of Person1
. How can I modify this code to correctly select the option with the value of 11
(Person1)?
Set value directly on the <select>
element
This is the easiest and most direct way. You just set the value of the <select>
element to the value you want. JavaScript handles the rest!
<a href="javascript:void(0);" onclick="document.getElementById('personlist').value = '11';">change</a>
Why it works:
You’re telling JavaScript, “Hey, make this dropdown select the option whose value is ‘11’.” This is the most straightforward JavaScript select option method.
Loop through the <option>
tags and set .selected
This one gives you more control, especially useful if the <select>
has dynamic options or you’re doing more custom logic:
<a href="javascript:void(0);" onclick="
const list = document.getElementById('personlist');
for (let i = 0; i < list.options.length; i++) {
if (list.options[i].value === '11') {
list.selectedIndex = i;
break;
}
}
">change</a>
Why it works:
You’re looping through each <option>
, comparing its value to ‘11’, and setting the dropdown’s selected index when you find a match. It’s a bit more code, but super clear and great for debugging.
Here’s a slick one-liner using querySelector, which is super helpful when you just want to target the right option immediately.
<a href="javascript:void(0);" onclick="
document.querySelector('#personlist option[value=\'11\']').selected = true;
">change</a>
Why it works:
It directly grabs the <option>
with value=“11” and marks it as selected. This JavaScript select option technique is elegant and great when you know exactly what you want.