Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if Enter Key was pressed within a DIV using jquery?

Tags:

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.

like image 367
Baig Avatar asked May 29 '13 10:05

Baig


People also ask

How do you detect if Enter is pressed?

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.

How do you check if Enter key is pressed JavaScript?

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.

Which jQuery event occurs when 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).

What is Keyup and Keydown in jQuery?

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.


1 Answers

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

like image 94
Amit Avatar answered Oct 08 '22 22:10

Amit