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?
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.
Use the ENTER's keycode 13.
$(".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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With