Reputation: 7100
Problem Statement: I have implemented code described in this Stack Overflow answer to try and capture a press of the answer key while a user is in a text <input>
. The code works to capture the enter press, however, after enter is pressed, the function body keeps running. Essentially, as soon as the enter key is pressed, the function runs infinitely. The ideal behavior of this is to have a user press Enter and then have the function called once.
What have I tried to solve my Problem?
The following was my original jQuery.
$(function(){
$("#maininput").keyup(function (e) {
if (e.keyCode == 13) {
alert("Enter was Pressed while in input ")
}
});
});
This ran infinitely after the Enter key was pressed. As a result of this, I started looking for more Stack Overflow entries, and I found threads like this that talk about using return false
or e.preventDefault()
. I tried implementing return false
and had the following code:
$(function(){
$("#maininput").keyup(function (e) {
if (e.keyCode == 13) {
alert("")
}
return false;
});
});
However, even the return false
didn't fix it. I then replaced return false
with e.preventDefault()
and that didn't work. A JSFiddle can be found here.
What is going wrong with my code and how can I fix it?
Upvotes: 0
Views: 84
Reputation: 40038
Nothing in the code you posted will cause the keyup
function to run repeatedly, but perhaps you need to debounce your function.
https://css-tricks.com/the-difference-between-throttling-and-debouncing/
http://benalman.com/projects/jquery-throttle-debounce-plugin/
Also, you were on the right track with return false
and e.preventDefault()
. Here is a great explanation of the difference between the two:
https://css-tricks.com/return-false-and-prevent-default/
Upvotes: 1