Here’s a JavaScript (jQuery) function I recently created which is called when the value of an input text box is changed through a key press, with a timed delay before the resulting action is processed.
For example this can be useful when updating quantities in a shopping cart and you don’t want the values to be updated instantly. Having a delay can give the user enough chance to enter new values or quantities in the text box before the desired action is triggered.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script> <script language="javascript" type="text/javascript"> (function($) { //In case jQuery no conflict is being used $(document).ready(function() { //wait for document ready var timer; var delay = 600; // 0.6 seconds delay after last input $('.inputfield').bind('input', function() { window.clearTimeout(timer); timer = window.setTimeout(function(){ //insert delayed input change action/event here $('#form1').submit(); }, delay); }) }); // END READY })(jQuery); </script>
The above jQuery function initiates a new timer element after the page has loaded and a delay variable is defined for 0.6 seconds. Whenever a new value is entered into an input box with the class inputfield, the timer element is reset and triggered after the delay value. In the example above, it is set to submit a form with ID form1.
Thanks for this code. I am using it to call two different function it works fine. But second part of code is never exectuted.
var timer;
var delay = 1000;
$(‘.inputfield’).bind(‘input’, function() {
window.clearTimeout(timer);
timer = window.setTimeout(function() {
$(‘#LastName #Email #LastName #FirstName #Order_Num’).on(‘input’, function() {
callSearch();
});
//below code never works
$(‘#Order_Num’).on(‘input’, function() {
var orderNum = $(‘#Order_Num’).val();
$.ajax({
async: false,
type: “GET”,
url: “ajax_getPartsTable.php”,
data: ‘Order_Num=’ + orderNum,
success: function(html) {
$(‘#RxPartsTable’).html(html);
}
});
});
}, delay);
})
I have mentioned in comment the part which doesnt work. Can you guide me what should I do?.
Note If I dont use time delay I mean the wrapper proper provided by you it does work.
Thanks mate. Got solution after proper investigation found that one of my internal function was hindering it.
This is a useful idea, but doesn’t the input event still trigger twice if two numbers are input, unless you unbind the input event after it fires once? That seems to be the case for me – a two digit number counts as two input events.
Also, just for future-proofing/nitpicking, probably better to use the “on” handler instead of “bind” these days, although it will obviously still work this way.