Im trying to assign an onKeyUp event to all inputs within a form, using closures. the array fields
contains all the names of the fields that require the event assigned to them. The array ajaxFields
contains the names of the fields (from the array fields
) that requires 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 would like the onKeyUp function to be executed a second after the user has finished typing in that field, insted of every time the key is up (onKeyUp). this would save up a lot of processing space, not to mention the ajax calls. So far im using this:
clearTimeout(timer);
timer = setTimeout('validate()' ,1000);
You might have noticed that the function validate()
doesn't exist, and thats because I dont know how to wrap the closures inside a named function, and im not even sure if I should...
So how do I do that?
EDIT: here is a current fiddle
This is what your code should look like:
Also checkout the fiddle for the working code: http://jsfiddle.net/BLyhE/
You can (and should) pass functions to
setTimeout
instead of strings.So, in your
keyup
, try something like this:I save the timeout in
$this.data
, so that each element can have its own timeout, instead of using a global variable.Updated Demo: http://jsfiddle.net/Z43Bq/3/