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?
Related videos on Youtube
Author by
Maverick
Updated on September 25, 2020Comments
-
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>
-
drudge about 13 yearsHaving multiple elements sharing the same
ID
is invalid HTML... -
ErichBSchulz over 10 yearsduplicate of stackoverflow.com/questions/1152738/…
-
-
Maverick about 13 yearsNope..its giving me the multiple of option tags.. for the above example its returning 6. But I need 2 as my answer.
-
manji about 13 yearsbecause you're giving the same id to all selects
-
drudge about 13 years@mad_programmer: Stop using IDs incorrectly and it won't be an issue.
-
manji about 13 yearsdon'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 anid='select1'
-> use$('select#select1 option').length
-
Pushpendra almost 13 yearsThanks, helped me in a similar situation.
-
Tomas almost 11 yearsJust 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 almost 10 yearsThis 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