Skip to main content

Bug Tracker

Side navigation

#12792 closed bug (notabug)

Opened October 26, 2012 02:33PM UTC

Closed October 26, 2012 03:02PM UTC

Last modified November 25, 2012 03:51AM UTC

index() returns incorrect value when two or more elements have identical "name" attribute values

Reported by: prometh@gmail.com 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>
Attachments (0)
Change History (3)

Changed October 26, 2012 02:40PM UTC by prometh@gmail.com comment:1

Please delete my ticket description and replace with:

http://jsfiddle.net/BvSxa/

Changed October 26, 2012 03:02PM UTC by dmethvin comment:2

resolution: → notabug
status: newclosed

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.

Changed November 25, 2012 03:51AM UTC by dmethvin comment:3

#12953 is a duplicate of this ticket.