selectedIndex Property in JavaScript

Sahil Bhosale Mar 07, 2022
selectedIndex Property in JavaScript

This article will tackle the select element index using JavaScript’s selectedIndex property.

Get Index of the select Element Using selectedIndex Property in JavaScript

The select is an HTML element that allows you to create a dropdown list. This HTML element can have various option elements as children.

The select element has a selectedIndex property that allows you to set or return the selected option index from the dropdown list. The index value starts with zero.

If you are selecting multiple options from the dropdown list, then, in that case, it will return the index as the first element from the list.

In this section, we will see how to get the index value of the selected element. We will use the selectedIndex property.

First, inside the HTML, we will create a select element. On this select element, we will set an id of dropdown and a click listener, which will call a function setSelectedIndex() as soon as a user clicks on it.

The select contains various option elements with some values.

<select id="dropdown" onclick="setSelectedIndex()">
    <option>Google</option>
    <option>Microsoft</option>
    <option>Apple</option>
    <option>Netflix</option>
    <option>Meta</option>
</select>

We will define the setSelectedIndex() function inside the JavaScript file. The setSelectedIndex() function aims to return the index of the element selected from the dropdown by the user.

We first have to get the reference of the select element using its id and then add the selectedIndex property to it. Then we will store the result inside a variable x and then print the value on the console.

<script>
    function setSelectedIndex() {
        var x = document.getElementById("dropdown").selectedIndex;
        console.log(x)
    }
</script>

Output:

selectedIndex_animation

Sahil Bhosale avatar Sahil Bhosale avatar

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.

LinkedIn