Skip to content Skip to sidebar Skip to footer

Javascript Onkeyup Closures With Timeout

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

Solution 1:

You can (and should) pass functions to setTimeout instead of strings.

clearTimeout(timer);
timer = setTimeout(function(){
    // your code here
}, 1000);

So, in your keyup, try something like this:

$('input[name='+fields[x]+']').keyup(function(field) { 
//assign an onKeyUp eventreturn function() {
        var that = this,
            $this = $(this);
        clearTimeout($this.data('timeout'));
        $this.data('timeout', setTimeout(function(){
            //some code using variable 'field' and array 'ajaxFields'// "this" will not be your element in here, make sure to use "that" (or "$this")
        }, 1000));
    };
}(fields[x]));

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/

Solution 2:

This is what your code should look like:

var timer;

$(document).ready(function() {
    var fields = $('.field');
    var ajaxFields = $('.ajax-field');

    createEvents(fields, ajaxFields);
});

functioncreateEvents(fields,ajaxFields) {
    // Use jQuery's "foreach" method
    $(fields).each(function(inx, field) {
        // Bind the listener here
        $(field).keyup(function(ev) {
            // Clear timeout if necessaryif (timer != null) clearTimeout(timer);

            // Set the timeout
            timer = setTimeout(function() {
                // Your code should hereconsole.log('Fields: ', fields, '\nAjax Fields: ', ajaxFields, '\nTHE field: ', field);
            }, 1000);
        });
    });
}

Also checkout the fiddle for the working code: http://jsfiddle.net/BLyhE/

Post a Comment for "Javascript Onkeyup Closures With Timeout"