Reputation: 10869
Desired Behaviour
Get accurate index number of <select>
element.
Current Behaviour
0
is returned regardless of actual index number.
jsFiddle
http://jsfiddle.net/rwone/hsp6jeLh/
HTML
<div class="my_class">
<select>
<option value="none">don't click me</option>
<option value="bar1">bar1</option>
</select>
</div>
<div class="my_class">
<select>
<option value="none">click me</option>
<option value="bar2">bar2 - select me</option>
</select>
</div>
jQuery
$(document).on("change",".my_class select", function() {
console.log($(this).index());
console.log("Why isn't the above value 1?")
});
Edit 01:
Ergh, just realised I should probably add a class to the select element and pass that through to the on()
method. Will try now...
No, that didn't work either: http://jsfiddle.net/rwone/hsp6jeLh/5/
Upvotes: 0
Views: 71
Reputation: 10869
User @Cattla's suggestion (which seems to be deleted) worked:
http://jsfiddle.net/hsp6jeLh/6/
$(document).on("change",".my_class", function() {
console.log($(this).index());
});
Upvotes: 0
Reputation: 11382
The index()
works only on adjacent elements. If you remove the closing and opening div
in the middle it works like you expect it:
<div class="my_class">
<select>
<option value="none">don't click me</option>
<option value="bar1">bar1</option>
</select>
<select>
<option value="none">click me</option>
<option value="bar2">bar2 - select me</option>
</select>
</div>
http://jsfiddle.net/hsp6jeLh/8/
Upvotes: 1