Get selected value of dropdown in JavaScript/jQuery on change
This post will discuss how to get the selected value of dropdown in JavaScript and jQuery onchange event.
1. Using jQuery
The idea is to bind the change event handler to the select box using the .change(handler) method. Now an alert is displayed whenever an option is selected from the dropdown.
jQuery
|
1 2 3 4 5 |
$(document).ready(function() { $('select').change(function() { alert(this.value); }); }); |
HTML
|
1 2 3 4 5 6 |
<select name="choice"> <option value="default" selected>Choose a Value</option> <option value="first">First Value</option> <option value="second">Second Value</option> <option value="third">Third Value</option> </select> |
Note that this.value won’t work with an arrow function. Use the following code instead:
jQuery
|
1 2 3 |
$(document).ready(function() { $('select').change(e => alert(e.target.value)); }); |
HTML
|
1 2 3 4 5 6 |
<select name="choice"> <option value="default" selected>Choose a Value</option> <option value="first">First Value</option> <option value="second">Second Value</option> <option value="third">Third Value</option> </select> |
The .change(handler) method is a shortcut for .on("change", handler). You can also do like:
jQuery
|
1 2 3 4 5 |
$(document).ready(function() { $('select').on('change', function() { alert(this.value); }); }); |
HTML
|
1 2 3 4 5 6 |
<select name="choice"> <option value="default" selected>Choose a Value</option> <option value="first">First Value</option> <option value="second">Second Value</option> <option value="third">Third Value</option> </select> |
2. Using JavaScript
In vanilla JavaScript, you can use the onchange property to specify an event handler to receive change events. Now, the onchange event handler is fired whenever a change is made to the select element.
HTML
|
1 2 3 4 5 6 |
<select id="choice" onchange="getValue(this);"> <option value="default" selected>Choose a Value</option> <option value="first">First Value</option> <option value="second">Second Value</option> <option value="third">Third Value</option> </select> |
JS
|
1 2 3 |
function getValue(option) { alert(option.value); } |
Note that it is bad practice to mix JavaScript with HTML markup. A better solution would be:
JS
|
1 2 3 |
document.getElementById('choice').onchange = function() { alert(this.value); } |
HTML
|
1 2 3 4 5 6 |
<select id="choice"> <option value="default" selected>Choose a Value</option> <option value="first">First Value</option> <option value="second">Second Value</option> <option value="third">Third Value</option> </select> |
That’s all about getting the selected value of dropdown in JavaScript and Query on change.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)