Working with dropdown lists in JavaScript

In this lesson, we will learn how to work with the select tag, which is a dropdown list. If you don't know how to work with this tag in HTML, then first study this tag in the manual at this link: select.

Let's see how to work with this tag through JavaScript. Let's say we have a dropdown list like this:

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

Get a reference to the select into a variable:

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

Let's now display the text of the selected list item when changing the select. To do this, we need to read the value property of our select:

select.addEventListener('change', function(){ console.log(this.value); });

Given a select, a paragraph, and a button. By clicking on the button, display the text of the selected list item in a paragraph.

Make a dropdown list of years from 2020 to 2030. When you select any item in the list, display a message about whether this year is a leap year or not.

value attribute

As a rule, the attribute value is added to list items. In this case, the value property of the select will not contain the text option, but the value of its value attribute.

Let's rewrite our select:

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

Let's check what the selected value is now equal to:

select.addEventListener('change', function(){ console.log(this.value); });

Make a dropdown list with the names of the days of the week. As value attributes of the list items, add the numbers of the days of the week from 1 to 7. After changing the list, display a message on the screen indicating whether the selected day is a weekend or a workday.

enru