Categories
JavaScript Answers

How to change a select value from JavaScript?

Spread the love

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.

By John Au-Yeung

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

Leave a Reply

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