Dennis Dennis - 1 month ago 8
jQuery Question

How do I call AJAX that runs after I finish typing a number in the HTML Input box?

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" />




Answer

Try this with the delay inside the if statement

$('#order').keyup(function() {
  if ($(this).val().length == 4) {
    console.log('do delay with ajax here')
  }
}