How to get SELECT dropdown list Selected value using JavaScript

← PrevNext →

In this post here, I’ll show you how to get the selected value in a SELECT dropdown list using plain old JavaScript. This is for the beginners.

Here’s a SELECT dropdown list with a default value.

<select id="sel" name="birds">
    <option value="">-- Select --</option>
    <option value="001">Hairy Woodpecker</option>
    <option value="002" selected>Brewer's Sparrow</option>
    <option value="003">White-tailed Hawk</option>
</select>
Try it

The value 002 (or text Brewer’s Sparrow) in the above dropdown list has the attribute selected, which shows the text Brewer’s Sparrow as default or selected option when you first load the page and the SELECT element. See this.

Now, I want to get the selected value (not the text), when I click a button. Here’s how I’ll do it.

<body>
    <select id="sel" name="birds">
        <option value="">-- Select --</option>
        <option value="001">Hairy Woodpecker</option>
        <option value="002" selected>Brewer's Sparrow</option>
        <option value="003">White-tailed Hawk</option>
    </select>
    
    <input type="button" value="Click it" onclick="selVal(sel)">
</body>
<script>
    let selVal = (ele) => {
    	alert('Value of the selected option: ' + ele.value);
    }
</script>
Try it

Simple isn’t it.

Note: If you want to get the selected text of a SELECT dropdown list using JavaScript, see this post.

Here’s another method. In this case, there is no default or selected option. Rather, I’ll get the value when someone selects an option from the dropdown list. The method is the same, except there is no button control and JS function is called using the onchange event.

<body>
    <select id="sel" name="birds" onchange="selVal(this)">
        <option value="">-- Select --</option>
        <option value="001">Hairy Woodpecker</option>
        <option value="002">Brewer's Sparrow</option>
        <option value="003">White-tailed Hawk</option>
    </select>
</body>
<script>
    let selVal = (ele) => {
    	alert('The selected value: ' + ele.value);
    }
</script>
Try it
Try this method too

In the above examples, I am passing the element as parameter to the JS function. You can avoid the parameter and do this.

let selVal = () => {
    let selValue = document.getElementById('sel').value;	// Simply, get the value.
    alert(selValue);
}

The first two methods that I have shared in the beginning are more popular among developers, since its more dynamic and you do not have to hardcode the SELECT element’s id.

Meanwhile, You can also do this: 👉 Populate a SELECT element dynamically with JSON data using Ajax and see if you can extract the selected value.

← PreviousNext →