Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 710
Maverick Avatar asked Apr 09 '11 00:04

Maverick


People also ask

How to get number of options in select in jQuery?

You will use the following command to determine if there are any options within the select box. var length = $('#selectBoxId > option'). length; console.

How can check select option length in jquery?

var length = $('#mySelectList > option'). length; This assumes your <select> list has an ID of mySelectList .

How do you count dropdown values?

querySelectorAll() method to the number of drop-down options. Since the options are created using the <options> tag within the document, you can use the . querySelectorAll() method to access the length as well as the value.


2 Answers

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

like image 54
manji Avatar answered Oct 23 '22 11:10

manji


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?

like image 1
James Avatar answered Oct 23 '22 12:10

James