Using a variable array to create jQuery blur events
I have a multidimensional array of form field ids and which type of error checking they have on them. I want to add a blur event to each of the error fields so when the user leaves it to go to the next field it will make sure the field is valid.
I created a for loop with the blur event creation and an alert to make sure the blur 开发者_JAVA技巧is being created for that field. The alert tells all the fields have the validation added, but when I go to test it on the page, no matter what field I'm leaving the blur event validates the last field in the array only.
Here is the function.
function SetErrorFields(fields) {
var ErrorFields = fields;
for (Field in ErrorFields) {
alert("Field: "+ErrorFields[Field][0]+" | Validations: "+ErrorFields[Field][1]);
$('#'+ErrorFields[Field][0]).blur(function(){
Validate(ErrorFields[Field][0],ErrorFields[Field][1]);
});
}
}
I've tried changing a couple of things, but either nothing has worked or things get worse. Bellow is a list of what I tried and the result.
Changed ErrorFields[Field][0] to Field[0], but that changes everything in the alert to "undefined".
Using the following code throws "x is undefined" errors, when leaving the field.
for (x=0; x<ErrorFields.length; x++) {
alert("Field: "+ErrorFields[x][0]+" | Validations: "+ErrorFields[x][1]);
$('#'+ErrorFields[x][0]).blur(function(){
Validate(ErrorFields[x][0],ErrorFields[x][1]);
});
}
And I can't figure out the each method.
There is a useful parameter called eventData. It lets you send data to an event when it's declared. The below works.
function SetErrorFields(fields) {
ErrorFields = fields;
for (Field in ErrorFields) {
alert(ErrorFields[Field][0]+" | "+ErrorFields[Field][1]+" | "+$('#'+ErrorFields[Field][0]).val());
$('#'+ErrorFields[Field][0]).blur({fld: ErrorFields[Field][0], err: ErrorFields[Field][1]}, function(event){
Validate(event.data.fld,event.data.err);
});
}
}
For a more indepth explanation on what it does go here.
精彩评论