Sometimes, we want to select a value in a select dropdown with JavaScript.
In this article, we’ll look at how to select a value in a select dropdown with JavaScript.
How to select a value in a select dropdown with JavaScript?
To select a value in a select dropdown with JavaScript, we can set the selectedIndex
value.
For instance, we write
<select style="width: 280px" id="mobility" name="mobility">
<option selected="">Please Select</option>
<option>K</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
to add a select drop down.
Then we write
document.getElementById("mobility").selectedIndex = 2;
to select the drop down with getElementById
.
Then we set its selectedIndex
property to the index of the option we want to select.
Conclusion
To select a value in a select dropdown with JavaScript, we can set the selectedIndex
value.