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

Baig picture Baig · May 29, 2013 · Viewed 53.3k times · Source

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.

Answer

Amit picture Amit · May 29, 2013

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