How to set the selected option of the select box with JavaScript?

Spread the love

Sometimes, we want to set the selected option of the select box with JavaScript.

In this article, we’ll look at how to set the selected option of the select box with JavaScript.

How to set the selected option of the select box with JavaScript?

To set the selected option of the select box with JavaScript, we can use the setAttribute method.

For instance, we write

<select id="gate">
  <option value="null">- choose -</option>
  <option value="Gateway 1">Gateway 1</option>
  <option value="Gateway 2">Gateway 2</option>
</select>

to add the select element.

Then we write

document
  .querySelector("#gate option[value='Gateway 2']")
  .setAttribute("selected", true);

to select the option element we want to select with querySelector.

And we call setAttribute with 'selected' and true to select the option.

Conclusion

To set the selected option of the select box with JavaScript, we can use the setAttribute method.

Leave a Reply

Your email address will not be published.