Asim Zaidi
Asim Zaidi

Reputation: 28284

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.

Upvotes: 121

Views: 187149

Answers (10)

Adam
Adam

Reputation: 44929

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.

Upvotes: 9

Vatsal
Vatsal

Reputation: 2128

With pure javascript you can just call the length on the id of the select box. It will be more faster. Typically with everything native javascript is performing better and better with modern browsers

This can be achieved in javascript by

     var dropdownFilterSite = document.querySelector( '#dropDownId' );  //Similar to jQuery

var length = dropdownFilterSite.length.

Good website for some learning

www.youmightnotneedjquery.com

A good video to watch by Todd Motto

https://www.youtube.com/watch?v=pLISnANteJY

Upvotes: 1

Munzilla
Munzilla

Reputation: 3855

Click here to see a previous post about this

Basically just target the ID of the select and do this:

var numberOfOptions = $('#selectId option').length;

Upvotes: 5

Sharjeel Aziz
Sharjeel Aziz

Reputation: 8535

Get the number of options in a particular select element

$("#elementid option").length

Upvotes: 5

nicholasklick
nicholasklick

Reputation: 1212

$('select option').length;

or

$("select option").size()

Upvotes: 3

second
second

Reputation: 28637

$('#dropdown_id').find('option').length

Upvotes: 3

user113716
user113716

Reputation: 322492

var length = $('#mySelectList').children('option').length;

or

var length = $('#mySelectList > option').length;

This assumes your <select> list has an ID of mySelectList.

Upvotes: 220

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

$("#mydropdown option").length

Or if you already got a reference to it,

$(myDropdown).find("option").length

Upvotes: 11

Rob Stevenson-Leggett
Rob Stevenson-Leggett

Reputation: 35679

$('#idofdropdown option').length;

That should do it.

Upvotes: 4

fantactuka
fantactuka

Reputation: 3334

alert($('#select_id option').length);

Upvotes: 3

Related Questions