How to delay the .keyup() handler until the user stops typing?

前端 未结 27 3288
半阙折子戏
半阙折子戏 2020-11-21 23:32

I’ve got a search field. Right now it searches for every keyup. So if someone types “Windows”, it will make a search with AJAX for every keyup: “W”, “Wi”, “Win”, “Wind”, “Wi

27条回答
  •  天命终不由人
    2020-11-22 00:11

    This worked for me where I delay the search logic operation and make a check if the value is same as entered in text field. If value is same then I go ahead and perform the operation for the data related to search value.

    $('#searchText').on('keyup',function () {
        var searchValue = $(this).val();
        setTimeout(function(){
            if(searchValue == $('#searchText').val() && searchValue != null && searchValue != "") {
               // logic to fetch data based on searchValue
            }
            else if(searchValue == ''){
               // logic to load all the data
            }
        },300);
    });
    

提交回复
热议问题