Get index of selected option with jQuery
To snag the index of the currently selected option in a dropdown list with jQuery, simply use $("select").prop("selectedIndex")
. It's as easy as making an instant coffee:
Be mindful that JavaScript arrays, like the world of programming, start at zero. Here, selectedIndex
now holds the zero-based index of the selected option.
The Breadcrumbs -->
Following native breadcrumbs with JavaScript
If you're feeling adventurous and want to venture into the wild lands of pure JavaScript, you can use the DOM's selectedIndex
property for the same information:
Fear not! Despite taking a break from jQuery, it does exactly the same job.
Listening for changes in the wind
Knowing when a change happens is the key. Using the .change()
event handler, we can set our code in motion once the user makes their choice. Remember: Timing is everything.
This code patiently waits for the document
to be ready
, ensuring all elements are geared up before we unleash the action.
Using .index()? Think twice, code once!
Sometimes, .index()
might seem like an ideal method, but beware of its tricky nature. It can throw temper tantrums with certain elements, especially when it's asked about option index within a select:
In this case, an option is directly targeted and asked to reveal its index. But .index()
might act up a bit across different browsers - it's just its nature you know. So always cross-check with the doc!
Giving it a val()
ue
At times, you might need the value instead of the index. Just like needing the lyrics instead of the track number. In such cases, .val()
hits the right chord:
This returns the value attribute
of the selected option, just like the song lyrics to our track number!
Setting the index? You bet!
Just like a DJ, you may want to set the track number to change the vibe:
With this line, we are now playing the third track in the queue.
Targeting the right crowd
A rule of the thumb when DJing with jQuery: always ensure your selectors target the right crowd:
This targets only those options that are direct children of the #dropDownMenuKategorie element. This DJ knows his crowd!
Can't fake the funk: Direct DOM manipulation
If disco of jQuery methods isn't your jam, and you're all about the old school funk, you might prefer direct DOM manipulation:
This approach gives you direct access to the selectedIndex
property, and runs smooth like a vinyl record.
Was this article helpful?