2

I have a fiddle and also same code below.

I want to achieve this --> user enters a (usually) 4-digit number, and when they are done, I want to run an AJAX call.

I have been trying to figure it out but so far it is not working.

var delay = (function() {
  var timer = 0;
  return function(callback, ms) {
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();



$('order').keyup(function(e) {
  delay(function() {
    if (e.which >= 48 && e.which <= 57) {
      console.log("INSIDE");
      $.ajax({
        type: "POST",
        dataType: "json",
        url: "/echo/json/",
        data: 'order=' + $(this).val(),
        cache: false,
        success: function(json) {
          $('#ref_job').empty();
          $.each(json, function(i, value) {
            $('#ref_job').append($('<option>').text(value).attr('value', value));
          });
        }
      });
    }

  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="text" id="order" />

3
  • how you determinate the end of the input? Count of numbers in the field? Commented Oct 18, 2016 at 21:41
  • preferably once user stops typing (okay to be determined by condition of "user does not type anything in the last 1000ms"). As a fall-back I could check if it is 4 digits. Commented Oct 18, 2016 at 21:42
  • Lodash and Underscore have debounce functions that might be helpful for this. Essentially you call the debounced function on every keystroke, and then your wrapped function will only be called after a break of 1000ms or whatever you set. Commented Oct 18, 2016 at 21:44

1 Answer 1

2

Try this with the delay inside the if statement

$('#order').keyup(function() {
  if ($(this).val().length == 4) {
    console.log('do delay with ajax here')
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

in this case though I will not do delay right? why would I do delay, when the entire number is already there
Yes you could do it instantly as it reaches the fourth character but a small delay could not hurt...lets say someone got to the fourth char and realized it was wrong then backspaced and typed another one. Your delay could prevent your function from firing twice and only fire when they pause on the fourth char. This would be personal preference though.
it worked for me... until it stopped ... when I realized some numbers are 5 characters and not 4. I was not able to do delay with ajax. that's why I asked in the first place .. I was just using the "does it equal 4" method for now
Change the keyup function to be >= 4 instead of == 4
this is not a delay, this is just run after condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.