zulox zulox - 1 year ago 80
jQuery Question

Detecting enter key pressed

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

for detecting shift key press using event object.



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.