Search code examples
javascriptphpkeyuponkeyup

How to delay the java script keyup() handler when user clear text field


I'm using JavaScript keyup() event for a single text box.

If someone types “Windows”, it will send an HTTP request for every keyup:

“W”, “Wi”, “Win”, “Wind”, “Windo”, “Window”, “Windows”

This is the desired behaviour.

When the user clears the text box empty, it gives an error.

This is the undesired behaviour.

Question

How can I stop an HTTP request being sent when the text box is cleared?


Solution

  • You can use AJAX to send information to the server (and get information for that matter):

    <?php
    
    if (isset($_POST['search'])) {
      echo json_encode($_POST);
      die();
    }
    
    ?>
    
    <form>
      <input id="search" type="text" name="search" />
    </form>
    
    <script>
    
    document.getElementById("search").addEventListener('keyup', function (e) {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "#", true);
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
          if (xhr.readyState == 4 && xhr.status == 200) {
            object = JSON.parse(xhr.responseText);
            console.log(object);
          }
        }
      }
      xhr.send("search=" + this.value);
    });
    
    </script>