I want to get the value of an input field and send an ajax request. If I use keyup or keypress or change, the value is available instantly and request is sent. I want to wait for the user e.g. for 1 or 2 seconds so that he types whole word and then send an ajax request. My code is like this to get the vlaue. Thanks.
var timeout = window.setTimeout(function() {
$('input#search').keyup(function() {
var key = $("#search").val();
console.log(key);
});
}, 1000);
clearTimeout(timeout);
You need to use a timer and then use clearTimeout it to reset it as the user types. This code will do what you want and here's a jsFiddle.
var Timer;
function Start() {
$('#TheInput').keyup(function () {
clearTimeout(Timer);
Timer = setTimeout(SendRequest, 1000);
});
}
function SendRequest() {
var key = $("#TheInput").val();
alert(key);
}
$(Start);
Every time you call the function, you should clear the timeout and set a new one, try this:
(function () {
var timeout = {};
var update = function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
var key = $('#search').val();
console.log(key);
}, 1000);
};
$('input#search').keyup(update);
$('input#search').change(update);
}());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With