Sometimes, we want to change a select value from JavaScript.
In this article, we’ll look at how to change a select value from JavaScript.
How to change a select value from JavaScript?
To change a select value from JavaScript, we set the selectedIndex
or value
property.
For instance, we write
<select id="select">
<option value="defaultValue">Default</option>
<option value="Option1">Option1</option>
<option value="Option2">Option2</option>
</select>
to add a select element.
Then we write
document.getElementById("select").selectedIndex = 0;
document.getElementById("select").value = "defaultValue";
to select the select element with getElementById
.
Then we set the first option as the value by setting selectedIndex
to 0 or setting value
to 'defaultValue'
.
Conclusion
To change a select value from JavaScript, we set the selectedIndex
or value
property.