Alex Rivera | Logout

Counting the number of options in a select drop down (multiple on same page)

Asked 2012-01-21T09:23:29.177
16

I am trying to output the number of options in a select drop down, but there are multiple ones on the same page.

For example:

<select name="select" class="drop">
   <option name="option" value="Option 1"></option>
</select>

<select name="select" class="drop">
   <option name="option" value="Option 1"></option>
   <option name="option" value="Option 2"></option>
   <option name="option" value="Option 3"></option>
</select>

So the first one would output (1) and the second would output (3).

I have this code but it outputs (4) - counting all options from all selects.

<script type="text/javascript">
$(function() {
   $(".date_number").text($(".drop option").length + " items");
});
</script>

Any help appreciated!

Edit
Report

1 Answer

2

Description

You get 4 because your jQuery selector matches for all the options on your page.

The basic question is, which select you want count ?

The best, for search engine optimization (for example), is you give the selects different ids. But you can use other jQuery selectors like :eq(), :first, :last or otherl too. It depends on what you want to do.

Samples

Different IDs's

<select id="select1" name="select" class="drop">
   <option name="option" value="Option 1"></option>
</select>

<select id="select2" name="select" class="drop">
   <option name="option" value="Option 1"></option>
   <option name="option" value="Option 2"></option>
   <option name="option" value="Option 3"></option>
</select>

<span class="date_number"/>

$(function() {
  $(".date_number").text($("#select2 option").length + " items")
});

Check out this jsFiddle Demonstration

:last Selector

$(function() {
    $(".date_number").text($(".drop:last option").length + " items")
});

Check out this jsFiddle Demonstration

More Information

answered 2012-01-21T09:51:17.153

Your Answer