Could someone please take a look at this?
You’ll see the first alert prints -1 whereas I was expecting 1. Anyone know why?
Basic code from the fiddle:
<input type="checkbox" value="0" />0
<input type="checkbox" value="1" />1
<input type="checkbox" value="2" />2
<input type="checkbox" value="3" />3
alert($(':checkbox').index("input[value='1']"));
alert($(':checkbox').index("input[value='0']"));
You have the selectors reversed:
Example: http://jsfiddle.net/RaV35/
When passing the
index()[docs] method a selector, the individual element for which you want the index is the element against which.index()is invoked.The selector you pass to
.index()represents the collection against which the element in the original jQuery object is tested.When the original jQuery object (on the left) also contains a collection, only the first one is tested for its index against the selector on the right. That’s why the one with
value="0"was working.