Skip to content
Advertisement

Determine when an user is typing

I am building a search box (input field) which should make a server call to filter a grid with the text being inserted on it but I need to make this in an smart way, I need to fire the server call only if the user has stopped. Right now I’m trying to implement it, but if someone knows how to do it I’ll be very pleased. Anyway, if I do it first I’ll post the answer here… Best Regards, Jaime.

Advertisement

Answer

  1. When a key is pressed:
    1. Check if there’s an existing timer – stop it if there is one
    2. start a timer.
  2. When the timer expires, call the server method.
var searchTimeout;
document.getElementById('searchBox').onkeypress = function () {
    if (searchTimeout != undefined) clearTimeout(searchTimeout);
    searchTimeout = setTimeout(callServerScript, 250);
};
function callServerScript() {
    // your code here
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement