My goal is to add an onKeyUp event to all input fields within a form using closures. The array fields
holds the names of the fields that need this event, while the array ajaxFields
contains the names of fields requiring ajax validation.
function createEvents(fields,ajaxFields) {
for(var x=0;x<fields.length;x++) {
$('input[name='+fields[x]+']').keyup(function(field) {
//assign an onKeyUp event
return function() {
//some code using variable 'field' and array 'ajaxFields'
}(fields[x]));
}
}
I want the onKeyUp function to trigger one second after the user finishes typing in the field, rather than every time a key is pressed. This optimization will save processing space and reduce unnecessary ajax calls. Currently, I am using the following logic:
clearTimeout(timer);
timer = setTimeout('validate()' ,1000);
You may have noticed that the function validate()
doesn't exist. This is because I am unsure how to encapsulate the closures inside a named function or if it's even necessary...
How can I accomplish this?
EDIT: Here is a live example on JSFiddle.