I have a textbox. I want to call a ajax callback function with some 2 second delay on every keyup.
How to implement this?
I have a textbox. I want to call a ajax callback function with some 2 second delay on every keyup.
How to implement this?
Using jQuery, but feel free to substitute your own JS library of choice:
var currentTimer = null;
input.bind('keyup', function () {
if (!currentTimer) {
currentTimer = true;
setTimeout(function() {
if (currentTimer) {
currentTimer = null;
// Do ajax call here
}
}, 2000);
}
});
I'm using jQuery here but you should get the point:
function callAjax() {
timer = null;
// handle all your ajax here
}
var timer = null;
$('input').keyup(function () {
// this will prevent you from reseting the timer if another key is pressed
if (timer === null) {
timer = setTimeout(callAjax, 2000);
}
});
If you're using jQuery, you can use the excellent delayedObserver plugin.
2 second after last key press or every key press?
<input type="text" id="txtBox" value="" width="200px"/>
<input type="text" id="txt" width="200px"/>
<script type="text/javascript">
$(document).ready(function(){
$("#txtBox").keyup(function(){
setTimeout(function(){
$("#txt").val($("#txtBox").val());//Here call ajax code
},2000);
});
});
</script>