0

I have made a bookmarklet that should highlight the password and username box on a webpage. It finds the password box, and seems to be locating the text box that is before it, but then it stops working. Here is my code:

<html>
<head>
</head>
<body>
<a href="javascript:var boxes= $(':text, :password');var selectionBox = $(':password'); selectionBox.css('background','red');for(var i = 0; i < boxes.length;i++){alert('loop');if(boxes[i] == selectionBox[0]){alert('Username box found');boxes[i-1].css('background','blue');alert('Success!');}}">Password box highlighter</a>
</body>

I get an alert box saying 'loop' a couple of times, then 'Username box found', but then it stops working on the next line, and no 'Success!' alert box. Does anybody know what I am doing wrong? Thanks.

EDIT: Here is the code spread out:

var boxes= $(':text, :password');
var selectionBox = $(':password');
selectionBox.css('background','red');
for(var i = 0; i < boxes.length;i++){
 alert('loop');
 if(boxes[i] == selectionBox[0]){
  alert('Username box found');
  boxes[i-1].css('background','blue');
  alert('Success!');
 }
}
Daniel Causebrook
  • 469
  • 1
  • 8
  • 20

1 Answers1

2

You're using boxes[i-1] (which is the same as using .get(i-1)) to get a DOM element from the jQuery collection. Try using .eq():

boxes.eq(i-1).css('background','blue');

DEMO: http://jsfiddle.net/HsDCs/3/

If you checked your browser's console, you would've seen that it was complaining that css isn't a property/method for that element.

References:

Ian
  • 50,146
  • 13
  • 101
  • 111