Counting the number of option tags in a select tag in jQuery
⚡TLDR
Get to the count of option
elements in a select
with jQuery in a snap, using the .length
property:
This little piece of code provides the total number of options in select#mySelect
. Great for those sudden needs to calculate available choices for users.
Getting animated with dynamic options
Conquer dynamic count
Working with select
elements often includes updating options on-the-fly. Stay on top of these changes using the .on()
method:
Master manipulations
Add a new option and then update the count:
Updated count, after the last option gets removed:
With a twist of specificity
Want to count specific option
elements only? Get creative with your selectors:
AJAX-loaded content handled right
When dealing with AJAX-loaded options, you might need to apply the selector after populating:
Embrace efficiency
When possible, using a cached selector is a wise move for performance:
The goofs to avoid
.size()
is deprecated as of jQuery 1.8. Stick with.length
.- IDs are unique, ensure yours is one of a kind in DOM.
- Skipped the Intro to jQuery lecture? Remember, jQuery starts counting from zero!
Linked
Was this article helpful?