Maverick
Maverick

Reputation: 2760

How to count number of option tags using jQuery?

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>

Upvotes: 18

Views: 64422

Answers (3)

Si Davies
Si Davies

Reputation: 11

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);
});

Upvotes: 1

manji
manji

Reputation: 47978

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

Upvotes: 63

James
James

Reputation: 399

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?

Upvotes: 1

Related Questions