How to count number of option tags using jQuery?

64,142

Solution 1

with jquery:

for a given select with an id:

$('select#selectid option').length

for all selects with a given class:

$('select.selectclass option').length

for all selects in the page:

$('select option').length

but you should give different Ids to each element in a html page

Solution 2

I found that I got more consistent results using the JQuery children() method, i.e.,

$('.productDetail_variant select').each(function() {
      var currSelectValue = $(this).children();
      alert(currSelectValue.length);
});

Solution 3

Tag IDs are supposed to be unique to a document. Do you plan to have all of these in the document tree at the same time?

Share:
64,142

Related videos on Youtube

Maverick
Author by

Maverick

Updated on September 25, 2020

Comments

  • Maverick
    Maverick over 3 years

    I have a question as to how can I calculate number of options tag when I have multiple select box with same class and id?

    Let's say I have three select boxes. And I want the size of select box, so that I can dynamically add new select box with the same options:

    <select id="selectid" class="selectclass">
        <option>1</option>
        <option>2</option>
    </select>
    
    <select id="selectid" class="selectclass">
        <option>1</option>
       <option>2</option>
    </select>
    
    <select id="selectid" class="selectclass">
        <option>1</option>
        <option>2</option>
    </select>
    
  • Maverick
    Maverick about 13 years
    Nope..its giving me the multiple of option tags.. for the above example its returning 6. But I need 2 as my answer.
  • manji
    manji about 13 years
    because you're giving the same id to all selects
  • drudge
    drudge about 13 years
    @mad_programmer: Stop using IDs incorrectly and it won't be an issue.
  • manji
    manji about 13 years
    don't remove the ids if you are using the fisrt option (with ids). Just give diffrent ids (selectid1, selectid2, selectid3) and replace #selectid with the id of your choice. For example, if you want options count for select with an id='select1' -> use $('select#select1 option').length
  • Pushpendra
    Pushpendra almost 13 years
    Thanks, helped me in a similar situation.
  • Tomas
    Tomas almost 11 years
    Just in case someone else finds this and thinks 'oh, this is a nice solution' it isn't. A select element remember can also have optgroups which would make the length wrong.
  • radtek
    radtek almost 10 years
    This works for me, not using optgroups. By the way specifying 'option' as children fixes the optgroups problem. In Chrome when I try size or length I always get 1 no matter what. Nice work! Here is the 1 liner: $('#select_id').children('option').length