How to detect a textbox's content has changed

后端 未结 15 2044
猫巷女王i
猫巷女王i 2020-11-22 16:10

I want to detect whenever a textbox\'s content has changed. I can use the keyup method, but that will also detect keystrokes which do not generate letters, like the arrow ke

15条回答
  •  不知归路
    2020-11-22 16:19

    I assume that you are looking to do something interactive when the textbox changes (i.e. retrieve some data via ajax). I was looking for this same functionality. I know using a global isn't the most robust or elegant solution, but that is what I went with. Here is an example:

    var searchValue = $('#Search').val();
    $(function () {
        setTimeout(checkSearchChanged, 0.1);
    });
    
    function checkSearchChanged() {
        var currentValue = $('#Search').val();
        if ((currentValue) && currentValue != searchValue && currentValue != '') {
            searchValue = $('#Search').val();
            $('#submit').click();
        }
        else {
            setTimeout(checkSearchChanged, 0.1);
        }
    }
    

    One key thing to note here is that I am using setTimeout and not setInterval since I don't want to send multiple requests at the same time. This ensures that the timer "stops" when the form is submitted and "starts" when the request is complete. I do this by calling checkSearchChanged when my ajax call completes. Obviously you could expand this to check for minimum length, etc.

    In my case, I am using ASP.Net MVC so you can see how to tie this in with MVC Ajax as well in the following post:

    http://geekswithblogs.net/DougLampe/archive/2010/12/21/simple-interactive-search-with-jquery-and-asp.net-mvc.aspx

提交回复
热议问题