How do I use the Enter key as an event handler (javascript)? [duplicate]

…衆ロ難τιáo~ 提交于 2019-11-30 18:50:34

You could make the button type submit, or you can use the onkeyup event handler and check for keycode 13.

Here's a list of key codes: Javascript Char codes/Key codes). You'll have to know how to get the keycode from the event.

edit: an example

HTML:

<input onkeyup="inputKeyUp(event)" ...>

Plain javascript:

function inputKeyUp(e) {
    e.which = e.which || e.keyCode;
    if(e.which == 13) {
        // submit
    }
}

Here is a working code snippet for listening for the enter key

$(document).ready(function(){

    $(document).bind('keypress',pressed);
});

function pressed(e)
{
    if(e.keyCode === 13)
    {
        alert('enter pressed');
        //put button.click() here
    }
}

Here is a version of the currently accepted answer (from @entonio) with key instead of keyCode:

HTML:

<input onkeyup="inputKeyUp(event)" ...>

Plain javascript:

function inputKeyUp(e) {
    if (e.key === 'Enter') {
        // submit
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!