Photo by Jen Theodore on Unsplash
Sometimes, we may want to change the selected drop-down option with JavaScript.
In this article, we’ll look at how to change an HTML selected option with JavaScript.
Set the value Property of the Select Drop Down
We can change the HTML select
element’s selected option with JavaScript by setting the value
property of the select
element object.
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>
<button id='apple'>
apple
</button>
<button id='orange'>
orange
</button>
We have a select drop down with some options and 2 buttons that sets the selected options when clicked.
Then we can add the following JavaScript code to set the options with the buttons:
const appleBtn = document.getElementById('apple')
const orangeBtn = document.getElementById('orange')
const select = document.querySelector('select')
appleBtn.addEventListener('click', () => {
select.value = 'apple'
})
orangeBtn.addEventListener('click', () => {
select.value = 'orange'
})
We get the 2 buttons with getElementById
.
And we get the select
drop down with querySelector
.
Then we call addEventListener
with 'click'
to add click listeners on the buttons.
And we set select.value
of each to the value that we want to select.
value
should be set to the value of the value
attribute for this to work.
Now when we click the buttons, we should see the selected value in the drop-down change to one we set in the click listener.
Conclusion
We can set the select option with the HTML select dropdown with JavaScript by setting the value
property.