Reputation: 9801
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']"));
Upvotes: 4
Views: 2469
Reputation: 707866
I'm not sure I understand why you have to use index()
at all. Why not just put it all in the selector:
$('input:checkbox[value="2"]');
You can see it work in this fiddle: http://jsfiddle.net/jfriend00/Xa6hA/
If you did want to do it in multiple stages, it would be more logical to me to do it like this:
$('input:checkbox').filter('[value="3"]');
This gets all the checkboxes, then filters that list down to just the ones with value="3"
which seems a lot more intuitive than the way index()
appears to work.
Upvotes: 0
Reputation: 322562
You have the selectors reversed:
Example: http://jsfiddle.net/RaV35/
// element---v collection----------v
alert($("input[value='0']").index(":checkbox"));
alert($("input[value='1']").index(":checkbox"));
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.
// v--- only the first is tested (and it has value="0")...
$(':checkbox').index("input[value='0']")
// ----------------------^ ...and it is at index 0 of this "collection"
Upvotes: 4
Reputation: 35294
You need to pass it a jQuery object: http://jsfiddle.net/ybKzJ/1/
alert($(':checkbox').index($("input[value='1']")));
alert($(':checkbox').index("input[value='0']"));
Edit:
No that doesn't seem right as the second one is working just fine.
...curious...
Upvotes: 0
Reputation: 7575
alert($(':checkbox[value='1']').index());
alert($(':checkbox[value='0']').index());
Upvotes: 0