Categories
JavaScript Answers

How to set an option’s selected attribute from dynamic created option with JavaScript?

Spread the love

Sometimes, we want to set an option’s selected attribute from dynamic created option with JavaScript/

In this article, we’ll look at how to set an option’s selected attribute from dynamic created option with JavaScript.

How to set an option’s selected attribute from dynamic created option with JavaScript?

To set an option’s selected attribute from dynamic created option with JavaScript, we set the selected property of the option.

For instance, we write

const country = document.getElementById("country");
country.options[country.options.selectedIndex].selected = true;

to select the select element with getElementById.

And we get the selected option with country.options[country.options.selectedIndex]

We set its selected property to true to make it selected.

Conclusion

To set an option’s selected attribute from dynamic created option with JavaScript, we set the selected property of the option.

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 *