Categories
JavaScript Answers

How to Programmatically Set the Value of a Select Element Using JavaScript?

Spread the love

Setting the value Property

One way to set the value of a select element is to set the value of the value property of a select element.

For instance, we can write the following HTML:

<select>
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="grape">Grape</option>
</select>

to create our select element with the options.

Then we can set the value property of the select element after selecting it with JavaScript by writing:

const select = document.querySelector('select')
select.value = 'orange'

We use querySelector to get the select element.

Then we just set the value property to the value of the value attribute of the option element that we want to pick to select a value.

Therefore, we should see that Orange is picked from the drop-down when we load the page.

Setting the selected Property of an Option Element to true

We can also set the selected property of an option element to true to set an option in the drop-down.

To do this, we write the following HTML:

<select>
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="grape">Grape</option>
</select>

Then we can get the options with the options property and set the selected property of an option by writing:

const select = document.querySelector('select')
select.options[1].selected = true

select.options has the options.

And we can access a choice by its index.

Then we cal set the selected property of it to true to pick it.

Since Orange is the 2nd option, it has index 1.

And so Orange is set as the selected choice in the dropdown.

By John Au-Yeung

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

2 replies on “How to Programmatically Set the Value of a Select Element Using JavaScript?”

Under “Conclusion,”

The following sentence doesn’t make sense:

“Or we can set the value property of the select element the value of the value attribute of the option element we want.”

Did you forget a word?

Leave a Reply

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