Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all options of a select using jQuery?

How can I get all the options of a select through jQuery by passing on its ID?

I am only looking to get their values, not the text.

like image 520
Ali Avatar asked Feb 26 '09 11:02

Ali


People also ask

How do I iterate through select options in jQuery?

Simple jQuery code snippet to loop select box options (drop down boxes) in a form to get the values and text from each option. Useful for manipulating values in form select boxes. $('#select > option'). each(function() { alert($(this).

How can I get multiple selected values of select box in jQuery?

With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.


2 Answers

Use:

$("#id option").each(function() {     // Add $(this).val() to your list }); 

.each() | jQuery API Documentation

like image 119
ybo Avatar answered Sep 23 '22 19:09

ybo


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>
like image 26
KooiInc Avatar answered Sep 19 '22 19:09

KooiInc