Get all selected values of a multi-select dropdown list with jQuery
This post will discuss how to get all selected values of a multi-select dropdown list with jQuery.
With jQuery, you can use the .val()
method to get an array of the selected values on a multi-select dropdown list.
JS
1 2 3 4 5 6 |
$(document).ready(function() { $('#submit').click(function() { var selected = $('#pets').val(); alert(selected); }) }); |
HTML
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select id="pets" multiple="multiple"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Get Selected Values</button> |
Alternatively, you can use the jQuery.map() instead, as shown below:
JS
1 2 3 4 5 6 |
$(document).ready(function() { $('#submit').click(function() { var selected = $("#pets :selected").map((_, e) => e.value).get(); alert(selected); }); }); |
HTML
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select id="pets" multiple="multiple"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Get Selected Values</button> |
If you need to process each array individually, you can use the .each()
method:
JS
1 2 3 4 5 6 7 |
$(document).ready(function() { $('#submit').click(function() { $("#pets :selected").each(function() { alert(this.value); }); }); }); |
HTML
1 2 3 4 5 6 7 8 9 10 |
<label for="pets">Choose your pets:</label> <select id="pets" multiple="multiple"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="rabbit">Rabbit</option> <option value="parrot">Parrot</option> </select> <button id="submit">Get Selected Values</button> |
That’s all about getting all selected values of a multi-select dropdown list with jQuery.
Also See:
Get selected values in a multi-select drop-down with JavaScript
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 :)