Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect the Enter key in a text input field

I'm trying to do a function if enter is pressed while on specific input.

What I'm I doing wrong?

$(document).keyup(function (e) {     if ($(".input1").is(":focus") && (e.keyCode == 13)) {         // Do something     } }); 

Is there a better way of doing this which would say, if enter pressed on .input1 do function?

like image 907
jQuerybeast Avatar asked Aug 15 '11 00:08

jQuerybeast


People also ask

How do you trigger button click on enter?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.

What is the Enter key in JavaScript?

Use the ENTER's keycode 13.


2 Answers

$(".input1").on('keyup', function (e) {     if (e.key === 'Enter' || e.keyCode === 13) {         // Do something     } });  // e.key is the modern way of detecting keys // e.keyCode is deprecated (left here for for legacy browsers support) // keyup is not compatible with Jquery select(), Keydown is. 
like image 63
Joseph Silber Avatar answered Sep 20 '22 14:09

Joseph Silber


event.key === "Enter"

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

const node = document.getElementsByClassName("input1")[0]; node.addEventListener("keyup", function(event) {     if (event.key === "Enter") {         // Do work     } }); 

Modern style, with lambda and destructuring

node.addEventListener("keyup", ({key}) => {     if (key === "Enter") {         // Do work     } }) 

If you must use jQuery:

$(document).keyup(function(event) {     if ($(".input1").is(":focus") && event.key == "Enter") {         // Do work     } }); 

Mozilla Docs

Supported Browsers

like image 37
Gibolt Avatar answered Sep 20 '22 14:09

Gibolt