Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect enter in input elements of a certain class

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?

like image 907
user961627 Avatar asked Dec 14 '12 18:12

user961627


People also ask

How do you trigger button click on enter?

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.

How do you search on enter in JS?

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.

How do you press Enter key programmatically in typescript?

You can use: var e = jQuery. Event("keypress"); e. which = 13; //enter keycode e.

How do you check if Enter key is pressed in jQuery?

To check if an “enter” key is pressed inside a textbox, just bind the keypress() to the textbox. $('#textbox').


2 Answers

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/

like image 185
David Rodrigues Avatar answered Oct 05 '22 16:10

David Rodrigues


check this one: http://jsfiddle.net/EJyyr/

used this html:

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

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

and this is the jQuery which logs the input text id

$('.large').keypress(function (e) {
   if(e.which ==13)
    console.log($(this).attr('id'));
});
like image 20
Jai Avatar answered Oct 05 '22 17:10

Jai