Bug Tracker

Opened 7 years ago

Closed 7 years ago

Last modified 7 years ago

#12792 closed bug (notabug)

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

Reported by: prometh@… 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 7 years ago by prometh@…

Please delete my ticket description and replace with: http://jsfiddle.net/BvSxa/

comment:2 Changed 7 years ago by dmethvin

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.

comment:3 Changed 7 years ago by dmethvin

#12953 is a duplicate of this ticket.

Note: See TracTickets for help on using tickets.