Dheyv
Dheyv

Reputation: 195

Jquery function to delay sometime after Keyup

I was using Jquery AJAX call to get some content for binding. I need to delay sometime to allow ajax call to perform the operation. I have seen examples using setTimeout in Javascript. But I dont know how to use it my case. I tried but its not working. Pls fix my code to work fine.

Code

    $('#ISBN').keyup(function () {
    window.setTimeout(function () {
        var value = $(this).val();
        var Cat = $(this).attr("Id");
        if (value == "" || value == '') {
            $('.Table').remove();
        }
        else {
            $.post('@Url.Action("AutoBibs", "PoDetails")', { Val: value, Category: Cat }, function (data) {

                if (Cat == "ISBN") {
                    $('.Table').remove();
                    $('#' + Cat).after('<div id="ISB" class="find" style="width: 10px !important; margin-left: 0px;"><span id="tablepartial"></span>');
                    $('#ISB').html(data);
                    $('#' + Cat).removeClass("wait");
                }                
          });
        }
    }, 2000);
});

Thanks

Upvotes: 0

Views: 2108

Answers (2)

Ram
Ram

Reputation: 144679

this within the context of setTimeout refers to window object not #ISBN element, you should declare the value variable outside the setTimeout context or cache the $(this) object.

var t = '';
$('#ISBN').keyup(function () {
    clearTimeout(t);
    var value = $(this).val(); // this.value
    // or cache the object
    // var $this = $(this); 
    t = setTimeout(function () {
    // var value = $this.val(); 
    // ...     
    }, 2000);
});

Upvotes: 5

Catalin
Catalin

Reputation: 11721

var searchTimeout = null;
$('#ISBN').keyup(function () {
    clearTimeout(searchTimeout);

    searchTimeout = setTimeout(function () {
        // Here you have the search method
    }, 500);
});

Upvotes: 0

Related Questions