How to Get the Value of Selected Option in a Select Box in JavaScript

Select box, also known as dropdown menu, is a commonly used element in HTML forms.

It allows users to select a single option from a list of predefined options.

In this tutorial, we will discuss how to retrieve the selected option value in a select box using JavaScript.


Getting the Select Element

The first step to retrieve the selected option value is to get the select element.

This can be done using the document.getElementById() method.

The method takes the id of the select element as an argument and returns the corresponding element.

For example, if the select element has an id of “mySelect”, we can get the element using the following code:

var select = document.getElementById("mySelect");

Retrieving the Selected Option Value

Once we have the select element, we can use the value property of the select element to retrieve the selected option value.

The value property returns the value of the selected option.

For example, the following code retrieves the selected option value:

var selectedOptionValue = select.value;

Using the selectedIndex Property

Another way to retrieve the selected option value is to use the selectedIndex property of the select element.

The selectedIndex property returns the index of the selected option in the options array.

We can then use the index to get the value of the selected option.

For example, the following code retrieves the selected option value using the selectedIndex property:

var selectedIndex = select.selectedIndex;
var selectedOptionValue = select.options[selectedIndex].value;

Conclusion

In this tutorial, we discussed how to retrieve the selected option value in a select box using JavaScript.

We discussed two methods to retrieve the selected option value – using the value property and the selectedIndex property.

With these methods, you can easily retrieve the selected option value in a select box and use it in your JavaScript code.