jQuery Select Option Count Example
While dealing with Select dropdown in a form, at times, it might be desirable to get count of select options for further processing. Now this is possible using the Server Side Programming language that you use but we will need to reload the page. And we want to avoid reloading the page. So in this article, I am going to share with you, how to get select options count using jQuery by means of a really simple example. So read on to find out more.
How to Get Select Options Count Using jQuery
In jQuery, Select Option Count refers to the sum of all the options available in that specific select dropdown. So to get the select options count using jQuery, let us assume that we have couple of select dropdowns in our form. One of the select dropdown contains list of cities & the other select dropdown contains list of states. So let’s see how to get the count of each of these select dropdowns when a button is clicked, using jQuery.
Example: Get Select Option Count using jQuery
<form name="form1" method="post" action="">
<p>
<label for="states">States</label>
<select name="states" id="states">
<option value="USA">USA</option>
<option value="UK">UK</option>
</select>
<label for="cities">Cities</label>
<select name="cities" id="cities">
<option value="AL" selected="selected">AL</option>
<option value="TX">TX</option>
<option value="CA">CA</option>
<option value="NY">NY</option>
</select>
</p>
<p>
<input type="submit" name="get_select_option_count_for_states" id="get_select_option_count_for_states" value="Get States Count">
<input type="submit" name="get_select_option_count_for_cities" id="get_select_option_count_for_cities" value="Get Cities Count">
</p>
</form>
<script type="text/javascript">
$('#get_select_option_count_for_states').click(function(e) {
alert('Number of States: ' + $("#states option").length );
e.preventDefault();
});
$('#get_select_option_count_for_cities').click(function(e) {
alert('Number of Cities: ' + $("#cities option").length );
e.preventDefault();
});
</script>That’s it!
Do you know of any other ways to get select option count using jQuery? Feel free to suggest by commenting below.