How to get all options of a select using jQuery?
Use:
$("#id option").each(function(){ // Add $(this).val() to your list});
I don't know jQuery, but I do know that if you get the select element, it contains an 'options' object.
var myOpts = document.getElementById('yourselect').options;alert(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit:
console.log( [...document.querySelector("#demo").options].map( opt => opt.value ) );
<select id="demo"> <option value="Belgium">Belgium</option> <option value="Botswana">Botswana</option> <option value="Burkina Faso">Burkina Faso</option> <option value="Burundi">Burundi</option> <option value="China">China</option> <option value="France">France</option> <option value="Germany">Germany</option> <option value="India">India</option> <option value="Japan">Japan</option> <option value="Malaysia">Malaysia</option> <option value="Mali">Mali</option> <option value="Namibia">Namibia</option> <option value="Netherlands">Netherlands</option> <option value="North Korea">North Korea</option> <option value="South Korea">South Korea</option> <option value="Spain">Spain</option> <option value="Sweden">Sweden</option> <option value="Uzbekistan">Uzbekistan</option> <option value="Zimbabwe">Zimbabwe</option></select>
$.map
is probably the most efficient way to do this.
var options = $('#selectBox option');var values = $.map(options ,function(option) { return option.value;});
You can add change options to $('#selectBox option:selected')
if you only want the ones that are selected.
The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map
function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.