Reputation: 1249
Are there any ways available in jquery to detect whether Enter key has pressed?
I know that we can use keycodes/charset to identify the Enter key press, but I do not need to hard code an integer value in my js script as it will become a magical number. I need to know whether there are any other possible ways to detect Enter key press, which is something like e.shiftKey
for detecting shift key press using event object.
Thanks.
Upvotes: 0
Views: 706
Reputation: 14659
This is the immediate way that people detect this particular event, but there are other ways to identify the number 13.
var DOM_VK_RETURN = 13;
$(document).on('keydown', function(e) {
var code = e.keyCode || e.which;
if(code == DOM_VK_RETURN) {
console.log("Enter key pressed");
}
});
However, if you do not want to use an integer to detect the key, we could use hexadecimal.
Upvotes: 0
Reputation: 72967
So, you want to detect the Enter key being pressed without hardcoding a 13
for the keycode.
Now, I could suggest using 6.5*2
as the keycode, then, but that'd be silly.
The real answer is that there is no built-in constant for the Enter key, like the Shift key has.
The reason Shift has it, is because that key is often pressed in combination with other keys. You can't detect a Shift keyDown
event when pressing Shift+A, for example, because the event for the modifier has passed already when you're handling the keyDown
event for the A.
Frankly, your only real option would be to hardcode a application-wide constant that says something along the lines of:
window.keyCodes = {
Enter: 13,
SomeKey: 99
}
Then you can check against it like this:
if(e.keyCode === keyCodes.Enter)
Or, it may be possible to write a function that compares the character of the entered key with a string that contains only a return, but then you'd just be hardcoding a return, any way.
Upvotes: 4
Reputation: 3870
The keycode for the enter key is : 13
if(e.keyCode == 13)
//do something...
Upvotes: 1