Changing the selected list item in JavaScript

In the previous lesson, we learned how to get the selected list item. Let's now change the selected item using JavaScript.

To do this, in the property value of the select, we write the value of the value attribute of the option that we want to select.

Suppose we have the following select:

<select id="select"> <option value="one">one</option> <option value="two" selected>two</option> <option value="three">three</option> </select>

Let's also have a button:

<input type="submit" id="button">

Get references to the select and the button into variables:

let select = document.querySelector('#select'); let button = document.querySelector('#button');

And now let's make it so that when the button is clicked, our select changes the selection:

button.addEventListener('click', function() { select.value = 'one'; });

If our list does not have value attributes, then we need to write the text of the option tag that we want to select into the value property of the select.

Make a dropdown list with the names of the months. Make JavaScript select the current month from this list by default.

enru