Choosing a jquery index () method method by attribute value

Can anyone take a look at this ?

You will see the first warning print -1, while I was expecting 1. Does anyone know why?

Base script code:

<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']")); 
+4
source share
4 answers

You have selectors:

Example: http://jsfiddle.net/RaV35/

  // element---v collection----------v alert($("input[value='0']").index(":checkbox")); alert($("input[value='1']").index(":checkbox")); 

When passing the selector index() [docs] method, a separate element for which you want the index to be the element against which .index() called.

The selector you pass to .index() represents the collection with which the element in the jQuery source object is checked.

When the source jQuery object (on the left) also contains a collection, only the first is checked for its index against the selector on the right. That is why it worked with value="0" .

  // 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" 
+4
source
 alert($(':checkbox[value='1']').index()); alert($(':checkbox[value='0']').index()); 
0
source

You need to pass the jQuery object: http://jsfiddle.net/ybKzJ/1/

 alert($(':checkbox').index($("input[value='1']"))); alert($(':checkbox').index("input[value='0']")); 

Edit:

No, this does not seem correct, since the second one works fine.

... curious...

0
source

I'm not sure I understand why you should use index() at all. Why not just put all this in a selector:

 $('input:checkbox[value="2"]'); 

You can see how this works in this script: http://jsfiddle.net/jfriend00/Xa6hA/

If you wanted to do this in several stages, it would be more logical for me to do it as follows:

 $('input:checkbox').filter('[value="3"]'); 

This gets all the checkboxes, and then filters that are listed only with value="3" tags, which seem more intuitive than the index() method that works.

0
source

All Articles