Get selected value from a drop-down list with JavaScript/jQuery
This post will discuss how to get selected value from a dropdown list in JavaScript and jQuery.
1. Using jQuery
With jQuery, you can use the .val() method to get the selected value from a dropdown. This can be done in several ways using the :selected property to get the selected option, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$("select option:selected").val(); $("select :selected").val(); $(":selected", $("select")).val(); $("select option").filter(":selected").val(); $("select").children("option").filter(":selected").val(); $("select").children("option:selected").val(); $("select").find("option:selected").val(); |
Here’s a live example:
JS
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $('#container').append(`The selected value is ` + $("#nums option:selected").val()); }) }); |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<label for="nums">Choose a value:</label> <select id="nums"> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> <option value="four">Four</option> </select> <button id="submit">Get Selected Value</button> <div id="container"></div> |
2. Using JavaScript
In plain JavaScript, you can do like:
JS
|
1 2 3 4 5 |
document.getElementById('submit').onclick = function() { var e = document.getElementById("nums"); var value = e.options[e.selectedIndex].value; document.getElementById("container").innerHTML = 'The selected value is ' + value; } |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<label for="nums">Choose a value:</label> <select id="nums"> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> <option value="four">Four</option> </select> <button id="submit">Get Selected Value</button> <div id="container"></div> |
Or use
JS
|
1 2 3 4 |
document.getElementById('submit').onclick = function() { var value = document.getElementById("nums").selectedOptions[0].value; document.getElementById("container").innerHTML = 'The selected value is ' + value; } |
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<label for="nums">Choose a value:</label> <select id="nums"> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> <option value="four">Four</option> </select> <button id="submit">Get Selected Value</button> <div id="container"></div> |
That’s all about getting the selected value from a drop-down list in JavaScript and jQuery.
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 :)