How to get the selected value of the dropdown list in JavaScript
1. Get the selected value of the dropdown list
We can use the value property of the selectbox to get the selected value of the dropdown list.
Explanation
In the above code:
- Lines 5 to 9: We create a
selectboxwith three options (one,two, andthree).
- Line 14: We create a variable with name
dropdownListand assign the createdselectboxas the value.
- Line 15: We bind an event listener for the change event on the
selectbox. The assigned function will be executed when the value of theselectboxchanges. Inside the function, we get thevalueproperty of the select box and print it. Thevalueproperty denotes the selected value of theselectbox.
2. Get the selected value and text of the dropdown list
If we want to get the selected option text, then we should use the selectedIndex property of the selectbox. The selectedIndex property denotes the index of the selected option. Once we get the selected index, we can access the selected option. From that, we can get the value and text of the option by accessing the value and text property, respectively.
Explanation
In the above code:
- Lines 5 to 9: We create a
selectboxwith three options (one,two, andthree).
- Line 14: We create a variable with name
dropdownListand assign the createdselectboxas the value.
- Line 15: We bind an event listener for the change event on the
selectbox. The assigned function will be executed when the value of theselectboxchanges.
- Lines 16 and 17: Inside the function, we get the
selectedIndexproperty of the select box and print it. It returns the index of the selected option element of theselectbox.
- Line 18: Using the
selectedIndexproperty, we get the selected option of theselectboxand store it in the variable with nameselectedOption.
- Lines 20 and 21: We access the
valueandtextproperty of theselectedOptionand print it.