Reputation: 43843
In my asp.net solution, I have a text input box and a search button. There is a onkeyup jquery event on the text input field so it automatically clicks the search button when the user presses a key. You can also manually click the button.
But what I noticed is that if you are typing, and then you press ENTER key, it will trigger the on onkeyup event. How can I disable the function from occurring if the ENTER key was pressed, or maybe detect if it was the ENTER key and then have an if statement or something.
Another thing that is happening is, if there is something wrong with the text in the input box, I display an alert message box. Then if you press ENTER to close the box, it will somehow trigger the onkeyup event, which displays the alert box again...
Thanks.
Upvotes: 2
Views: 6191
Reputation: 20737
For future reference I found this useful site:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Good luck!
Upvotes: 0
Reputation: 2064
The onkeyup
event is triggered after an alert when you close it with ENTER because the alert is close onkeydown
, and so after it's closed and the document regains focus, when you release the key, the textbox's onkeyup
event will be triggered.
As previously stated, you can add an if (event.keyCode != 13)
to test if the ENTER key is not the key that was pressed.
A better solution would be to use a different event.
Instead of onkeyup
, use oninput
.
The oninput
event is triggered when the user changes the textbox's value.
The event will fire only when the user writes something in the textbox or deletes something. It will not go off when the ENTER key is pressed, or when any other key that doesn't change the textbox's value (like arrow keys) is pressed.
The oninput
event might be a better choice for the functionality you're searching for.
*if you're using the oninput
event you don't need the if
mentioned before.
A fiddle for demonstration of the oninput
event: Here
Upvotes: 1
Reputation: 56
You can use .which on the event to determine the KeyCode for the key that was pressed (ENTER = 13):
$('#input').keyup(function(event) {
if(event.which == 13)
{
//respond to enter keypress
}
});
Also you can use this site to easily find info about keyups/downs etc for different keys.
Hope this helps!
Upvotes: 2
Reputation: 1478
add if (evt.keyCode != 13)
in front of all actions in the function :)
Upvotes: 5
Reputation: 159
Hope this helps.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
Upvotes: 1