I have an input field and a login button. I want to allow users to hit the "enter" key to click the button when the input field is focused. How would I do this with jQuery?
<input type="text" size="10" id="loginUserID" name="username"> <input type="button" value="Login" name="loginBtn" id="loginBtn">
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.
They both use a custom jQuery selector that I add called :focusable to select all focusable element (including links): // register jQuery extension jQuery. extend(jQuery. expr[':'], { focusable: function (el, index, selector) { return $(el).is('a, button, :input, [tabindex]'); } }); $(document).
We can do it by using “keyup”, “keydown”, or “keypress” event listener on textbox depending on the need. When this event is triggered, we check if the key pressed is ENTER or not.
Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.
$('#loginUserID').keypress(function(event){ if(event.keyCode == 13){ $('#loginBtn').click(); } });
Demo: http://jsfiddle.net/Bhf5a/
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