How do I check how many options there are in a dropdown menu?
How do I check, using jQuery, how many options are there in a drop down menu?
Thanks.
Solution 1:
var length = $('#mySelectList').children('option').length;
or
var length = $('#mySelectList > option').length;
This assumes your <select>
list has an ID of mySelectList
.
- http://api.jquery.com/length/
- http://api.jquery.com/children/
- http://api.jquery.com/child-selector/
Solution 2:
$("#mydropdown option").length
Or if you already got a reference to it,
$(myDropdown).find("option").length
Solution 3:
Use the length property or the size method to find out how many items are in a jQuery collection. Use the descendant selector to select all <option>
's within a <select>
.
HTML:
<select id="myDropDown">
<option>1</option>
<option>2</option>
.
.
.
</select>
JQuery:
var numberOfOptions = $('select#myDropDown option').length
And a quick note, often you will need to do something in jquery for a very specific thing, but you first need to see if the very specific thing exists. The length property is the perfect tool. example:
if($('#myDropDown option').length > 0{
//do your stuff..
}
This 'translates' to "If item with ID=myDropDown has any descendent 'option' s, go do what you need to do.
Solution 4:
Get the number of options in a particular select element
$("#elementid option").length