Categories
JavaScript Answers

How to change the selected option of an HTML select element with JavaScript?

Spread the love

Sometimes, we want to change the selected option of an HTML select element with JavaScript.

In this article, we’ll look at how to change the selected option of an HTML select element with JavaScript.

How to change the selected option of an HTML select element with JavaScript?

To change the selected option of an HTML select element with JavaScript, we can set the value property of the select element.

For instance, we write

<select id="sel">
  <option value="1">Cat</option>
  <option value="2">Dog</option>
  <option value="3">Fish</option>
</select>

to add the select element.

Then we write

document.getElementById("sel").value = "2";

to set the selection option to the 2nd option by selecting the select drop down with getElementById and setting its value to `’2′.

Conclusion

To change the selected option of an HTML select element with JavaScript, we can set the value property of the select element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to change the selected option of an HTML select element with JavaScript?”

Hello, this is a good solution when all options have a value, but is common to have an empty option disabled as indicator to make a selection, and normally that option is disabled to, so if we have
Please select an option
that solution will not work.

Leave a Reply

Your email address will not be published. Required fields are marked *