Detect enter in input elements of a certain class

user961627 picture user961627 · Dec 14, 2012 · Viewed 15.1k times · Source

I need to detect when someone hits "enter" in text inputs with a specific class.

My jQuery is as follows:

$('input.large').keypress(function (e) {
    if(e.which ==13)
        console.log("pressed enter");
});

My HTML is something like this:

<tr><td> Personal Name </td></tr>
<tr><td> <input type='text' class='large'> </td></tr>

<tr><td> Email</td></tr>
<tr><td> <input type='text' class='large'> </td></tr>

When I've given the fields IDs and tried $('#elementid').keypress it worked. But this isn't working. I get no console output. What am I missing?

Answer

David Rodrigues picture David Rodrigues · Dec 14, 2012

You can use live (.on()) events in document with keydown (I think this is better). It'll allow you detect keydown in current and future elements that matches with a selector.

HTML:

<strong>Personal Name</strong>
<input type='text' class='large' /><br />

<strong>Email</strong>
<input type='text' class='large' />
​

JS (jQuery 1.7+):

Note: .which, .code, .charCode and .keyCode is now deprecated. Use the following new solution:

jQuery(document).on('keydown', 'input.large', function(ev) {
    if(ev.key === 'Enter') {
        // Will change backgroundColor to blue as example
        this.style.backgroundColor = '#EFF';

        // Avoid form submit
        return false;
    }
});

jsFiddle: http://jsfiddle.net/david_proweb/fjgvhubn/2/