If you are exploring JavaScript to enhance your programming skills, then this is the best place for you to understand the basic concepts of JavaScript. In today’s guide, you will learn to extract the value which is selected in a dropdown list by utilizing JavaScript.
In this article, users will be able to get the value which is selected in the dropdown view by utilizing JavaScript.
How to Get Selected Value in a Dropdown List in JavaScript?
JavaScript can be used to retrieve values that are selected from the dropdown list and then display the value in the browser. This section provides a built-in function to get the value which is selected by the dropdown list.
Example
An example is demonstrated to get the values from a dropdown list in JavaScript.
Code
<html>
<head>
<title>Please select the element and see value</title>
<h2>An example to get selected value in dropdown list using JavaScript </h2>
<style>
* {font: 18px Arial;}
</style>
</head>
<body>
<p>Please select the element and see value </p>
<select id="sel" name="Sports">
<option value="">-- Please Select --</option>
<option value="Cricket">Cricket</option>
<option value="Football" selected>Football</option>
<option value="Hockey">Hockey</option>
</select>
<input type="button" value="Please Click it" onclick=" selectVal(sel)">
</body>
<script>
let selectVal = (ele) => {
alert('Return the value of the selected option: ' + ele.value);
}
</script>
</html>
The code is described as:
- First, a message is displayed to select the element from the dropdown list.
- After that, the option keyword is utilized for dropdown lists such as Cricket, Football, and Hockey.
- After clicking on each element, the piece of code is executed and pops up the values associated with the element.
Output
The display represents a dropdown list by executing the above code. At the backend, different elements are attached to a list, and each is assigned a value. By clicking an element, the specific value is displayed in the pop-up window.
Conclusion
A dropdown list is utilized to get the selected value by clicking the options in JavaScript. For this purpose, <select> and <option> tags are employed for selection and giving options to the users, respectively. By clicking the option, the user extracts the associated value in the pop-up window of the web browser. Mostly, these dropdown lists are used on e-commerce sites. Here, you have learned to get the value which is selected in dropdown lists using JavaScript.