Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make post call if text box content has not changed for X seconds

I have the following code block that sends the contents of a text input with id searchBox to a server using jQuery.

$(document).ready(function () {    
  $('#searchBox').on('input', function () {
    var searchContent = $(this).val()


    if (searchContent.length == 0) {
      // other not relevant code
    }
    else {    
   

        $.post('/checkAvailability',
          { domainName: searchContent },
          function (data, status, jqXHR) {
            console.log(status + ' ' + data);
          });

    }
  });
});

How can I call the $.post function only if the search content has not changed for 3 seconds?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Without using another implementation like lodash.throttle or lodash.debounce, you could use setTimeout and clearTimeout.

(I commented out the call to $.post and just used a console.log() call for the demo)

$(document).ready(function() {
  let run;

  $("#searchBox").on("input", function() {
    const searchContent = $(this).val();
    clearTimeout(run);

    if (searchContent.length == 0) {
      // other not relevant code
    } else {
      run = setTimeout(() => {
        console.log(searchContent);
        /* $.post(
          "/checkAvailability", {
            domainName: searchContent
          },
          function(data, status, jqXHR) {
            console.log(status + " " + data);
          }
        ); */
      }, 3000);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="searchBox" />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading