I have successfully hooked the EnterKey event at the document level as following:
$(document).keypress(function (e) { if (e.which == 13) { alert('You pressed enter!'); } });
But, I am unable to hook the EnterKey event on a Div with id "myDiv".
<div id="myDiv"></div> $("#myDiv").keypress(function (e) { if (e.which == 13) { alert('You pressed enter!'); } });
Is it possible to detect an EnterKey press within a Div? Actually, the Div contains some input/select controls which are used to filter the content of a Grid. I want to hook the EnterKey event so that when the EnterKey is pressed I can filter the Grid.
EDIT: Please note that I have inputs within the div(I've intentionally not shown them here). I don't want to hook the event manually for each of the input control within the Div. Also, I am assuming that when user presses EnterKey at least one input control shall have focus.
Check the event.The keyCode property returns a number for the key that's pressed instead of a string with the key name. When it returns 13, then we know the enter key is pressed.
Using JavaScript In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.
The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).
jQuery keyup() Method The order of events related to the keyup event: keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.
Try this
<div id="Div1"> <input type ="text" id="aa"/> sdfsd hsjdhsj shdj shd sj </div>
Jquery
$(function(){ $("#Div1 input").keypress(function (e) { if (e.keyCode == 13) { alert('You pressed enter!'); } }); });
Demo
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