HTML:
<input id="email" name="email" type=text />
<input id="password name="password" type="password" />
JavaScript:
var fields = ["email","password"];
for (var i in fields) {
var field = $("#"+fields[i]);
field.bind({
focus: function() {
field.css("border-color","#f00");
},
blur: function() {
field.css("border-color","#000");
}
});
}
My desire action will be as follows:
- When I place cursor on any of the above fields the input field’s border will be red.
- When I take away the cursor from the field it’s border will be black.
But the event is occurs only for the password filed whether I place and take away cursor form any of the above fields.
This is a really common problem, the
fieldvariable accessed on thefocusandblurevent belongs to the outer scope, so it contains the last iterated value, in your case it will contain"password".There are a lot of ways to solve this, for example you could use
$.eachwhich introduces a new scope:Or using
$(this)instead offieldin your event handlers, i.e.:Off-topic note: also in the above example that I use a normal loop, instead the
for...instatement, which is not really meant to be used on array-like objects.Try out the two code examples here.