Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of option tags in a select tag in jQuery

People also ask

How do I get the number of options in select?

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

How do you count options?

You can calculate the value of a call option and the profit by subtracting the strike price plus premium from the market price. For example, say a call stock option has a strike price of $30/share with a $1 premium, and you buy the option when the market price is also $30. You invest $1/share to pay the premium.

How do I count the number of elements in jQuery?

To count all HTML elements, we use length property. The length property is used to count number of the elements of the jQuery object. where selector is the object whose length is to be calculated.


$('#input1 option').length;

This will produce 2.


The W3C solution:

var len = document.getElementById("input1").length;

You can use either length property and length is better on performance than size.

$('#input1 option').length;

OR you can use size function like (removed in jQuery v3)

$('#input1 option').size(); 

$(document).ready(function(){
   console.log($('#input1 option').size());
   console.log($('#input1 option').length);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select data-attr="dropdown" id="input1">
   <option value="Male" id="Male">Male</option>
   <option value="Female" id="Female">Female</option>
</select>

Your question is a little confusing, but assuming you want to display the number of options in a panel:

<div id="preview"></div>

and

$(function() {
  $("#preview").text($("#input1 option").length + " items");
});

Not sure I understand the rest of your question.


In a multi-select option box, you can use $('#input1 :selected').length; to get the number of selected options. This can be useful to disable buttons if a certain minimum number of options aren't met.

function refreshButtons () {
    if ($('#input :selected').length == 0)
    {
        $('#submit').attr ('disabled', 'disabled');
    }
    else
    {
        $('#submit').removeAttr ('disabled');
    }
}

Ok, i had a few problems because i was inside a

$('.my-dropdown').live('click', function(){  
});

I had multiples inside my page that's why i used a class.

My drop down was filled automatically by a ajax request when i clicked it, so i only had the element $(this)

so...

I had to do:

$('.my-dropdown').live('click', function(){
  total_tems = $(this).find('option').length;
});