Text field change detection with jQuery --Basics of Incremental Search

How to detect changes in text fields with jQuery. This is the basic knowledge when implementing incremental search.

You can use the input event to detect that the text has changed.

Sample to detect text field changes with jQuery

This is a sample that detects changes in text fields with jQuery. When I type in the text field, "The text field has changed" is displayed.

Change detection:

<script src = "https://code.jquery.com/jquery-3.4.1.min.js"> </script>
<script>
  $(function () {
    / * Detects key input * /
    $(document) .on ('input','[name = foo]', function () {
      var foo_text = $('[name = foo]'). val ();
      $('.changed_text'). text ('Change detection:' + foo_text);
    });
  });
</script>

<div class = "changed_text">
  Change detection:
</div>

<input type = "text" name = "foo">

Wait if the next character is entered by changing the text field

The above method will pick up all input events as they are typed.

For example, if you type "Kimoto", the event will occur 7 times, such as "k", "ki", "kim", "kimo", "kimo t", "kimoto", and "kimoto".

I don't like the fact that many requests are sent when doing an incremental search.

How can I send a small number of requests?

Use the following algorithm.

Wait 1 second and detect if the next input has not been made. If the following is not entered, it means that the characters have not changed.

Implement using the setTimeout function and closures to store previous values ​​in closure variables.

Change detection:

<script src = "https://code.jquery.com/jquery-3.4.1.min.js"> </script>
<script>
  $(function () {
    / * Detects key input * /
    $(document) .on ('input','[name = foo_wait]', function () {
      / * Save the current value of the text field in a closure variable * /
      var save_one_second_before_wait_text = $('[name = foo_wait]'). val ();
      
      / * Run Closure * /
      var closure = function () {
        setTimeout (function () {
          var foo_wait_text = $('[name = foo_wait]'). val ();
          / * Execute processing if it is different from the previous value * /
          if (save_one_second_before_wait_text === foo_wait_text) {
            $('.changed_text_wait'). text ('Change detection:' + foo_wait_text);
          }
        }, 1000);
      };;
      closure ();
    });
  });
</script>

<div class = "changed_text_wait">
  Change detection:
</div>

<input type = "text" name = "foo_wait">

Associated Information