Run javascript function when user finishes typing instead of on key up?

前端 未结 29 2710
我寻月下人不归
我寻月下人不归 2020-11-22 04:03

I want to trigger an ajax request when the user has finished typing in a text box. I don\'t want it to run the function on every time the user types a letter because that wo

29条回答
  •  梦谈多话
    2020-11-22 04:42

    I was implementing the search at my listing and needed it to be ajax based. That means that on every key change, searched results should be updated and displayed. This results in so many ajax calls sent to server, which is not a good thing.

    After some working, I made an approach to ping the server when the user stops typing.

    This solution worked for me:

    $(document).ready(function() {
        $('#yourtextfield').keyup(function() {
            s = $('#yourtextfield').val();
            setTimeout(function() { 
                if($('#yourtextfield').val() == s){ // Check the value searched is the latest one or not. This will help in making the ajax call work when client stops writing.
                    $.ajax({
                        type: "POST",
                        url: "yoururl",
                        data: 'search=' + s,
                        cache: false,
                        beforeSend: function() {
                           // loading image
                        },
                        success: function(data) {
                            // Your response will come here
                        }
                    })
                }
            }, 1000); // 1 sec delay to check.
        }); // End of  keyup function
    }); // End of document.ready
    

    You will notice that there is no need to use any timer while implementing this.

提交回复
热议问题