简体   繁体   中英

Event handling issue in JavaScript

There is a textbox which is associated with an onkeyup event listener (a JavaScript function, say that alerts something). For an example-

<input type='text' name='text1' onkeyup='exec(this.value);'/>
<script>
exec = function(textdata) { alert(textdata); }
</script>

In this case the alert message will come each time the user hits something on the keyboard.

Is there any way of even handling, where in the event handler will proceed only after a few seconds of inactivity. that is, in this case the alert message will come only if the user has done typing a long text, and is thinking if he wants to add something more or not. For example, he types in his first name and waits for 2 second and after that the alert message appears, and alert message does not appears while he types in each letter of his first name.

You need to use onkeyup rather than onchange if you wish to run a function every time a key is pressed. Try this for the functionality you want

<input type='text' name='text1' onkeyup='exec(this.value);'/>
<script>

var timer; //This needs to be a global variable

exec = function(textData){

  clearTimeout(timer);

  timer = setTimeout(function(){ alert(textData) }, 2000);  
}
</script>

Every time the user presses a key (enters a character into the textbox) the function is called and the timer is cleared. The timer is then set to alert the textbox's value after 2 seconds, if they again press any keys before the 2 seconds has elapsed the timer is reset. Here is a working jsFiddle.

In your code, the text is only alerted each time you leave the textbox. That is the behavior of onchange . You need to lose focus on the item before it is triggered.

onkeyup will alert() each time a user presses something while in the textbox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM