简体   繁体   中英

JQuery Event for when user presses enter?

在文本框中输入后,只要用户点击进入,就会调用函数的最简单方法是什么?

You'll need to listen for the keypress event. It's probably easiest to do this with delegate :

$(document.body).delegate('input:text', 'keypress', function(e) {
    if (e.which === 13) { // if is enter
        e.preventDefault(); // don't submit form

        // do what you want here
    }
});
<textarea id="text"></textarea>

$('#text').keydown(function(e){
    if (e.keyCode == 13) {
        alert('Enter was pressed.');
    }
});

http://jsfiddle.net/dNfC2/

HTML code

<input type="text" id="txt"/>
<input type="button" id="btn" value="send"/>

jquery code

$("#txt").keydown(function(event){
if(event.keyCode == 13){
alert("enter button pressed");
$("#btn").click();
}
});

Running example here : http://jsfiddle.net/Xamkp/5/

try this:

jQuery(document).bind('keydown', 'return',function (){ /*do something*/ });

you will need a plugin: jquery.hotkeys

Well it's rather simple to do in the form you asked:

$('#idOfTextBox').keyup(function(event){
     // enter key pressed
     if(event.keyCode=='13')yourFunction();
});

Take note this will still append the enter key to the box. You might wanna try keydown or keypressed if you don't want that.

Be sure to check keyUp() for more detail.

Put the <input> in a form, and write a handler for the form's submit event.

This way you're not explicitly looking for any particular key; you're just waiting for the form to be submitted normally. And in every mainstream browser, pressing enter while filling out a form will submit the form.

Note that you do not need to have a physical submit button on the screen if you don't want (in which case the enter key will likely be the only way to submit the form).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM