#12792 closed bug (notabug)
index() returns incorrect value when two or more elements have identical "name" attribute values
Reported by: | Owned by: | ||
---|---|---|---|
Priority: | undecided | Milestone: | None |
Component: | unfiled | Version: | 1.8.2 |
Keywords: | Cc: | ||
Blocked by: | Blocking: |
Description
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Ricochet</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> </head> <body> <aside id="form1"> <input type="text" name="username" placeholder="username"/> <input type="password" name="password" placeholder="password"/><!--notice the name attribute--> <button type="submit">Sign In</button> </aside> <aside id="form2"> <input type="password" name="password" placeholder="Create Password"/><!--notice the name attribute--> <input type="password" name="verify" placeholder="Verify Password"/> <button type="submit">Sign In</button> </aside> <script type="text/javascript"> var fields = $("#form2 > input[type=password]"); var password = fields.eq( fields.index("[name=password]") ); var verify = fields.eq( fields.index("[name=verify]") ); // This will erroneously set VERIFY's bgcolor password.css("background-color", "gold"); // Gives "1", when it should be 0.. console.log( fields.index("[name=password]") ); // .. as you can see console.log(fields); </script> </body> </html>
Change History (3)
comment:1 Changed 10 years ago by
comment:2 Changed 10 years ago by
Resolution: | → notabug |
---|---|
Status: | new → closed |
You've got the needle and the haystack backwards. From the docs:
.index( selector )
-selector
A selector representing a jQuery collection in which to look for an element. If a selector string is passed as an argument, .index() returns an integer indicating the position of the original element relative to the elements matched by the selector. If the element is not found, .index() will return -1. -- http://api.jquery.com/index/
The term "original element" is confusing here, it means "first element in the jQuery object". So in this case the set is your two password fields and the first element in the set is the "Create password" element. The selector selects all name="password"
elements and your first element is the second (index 1) in the matched elements. I've updated the docs.
BTW there are MUCH better ways to do this, but that's a topic for the forum.
Please delete my ticket description and replace with: http://jsfiddle.net/BvSxa/