How to get all options of a select using jQuery?
Use:
$("#id option").each(function()
{
// Add $(this).val() to your list
});
.each() | jQuery API Documentation
Without jQuery
I do know that the HTMLSelectElement
element contains an options
property, which is a HTMLOptionsCollection
.
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit (using .querySelectorAll
, spreading the resulting HTMLOptionsCollection
to Array
and map the values).
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>