How do I use the Enter key as an event handler (ja

2019-02-13 06:25发布

问题:

This question already has an answer here:

  • execute function on enter key 7 answers

im trying to make my own chat... so i have an input text field, the submit button, isn't even submit, its just a button.... so when the enter key is pressed, i need the value of the input field to appear in my textarea (which is readonly)...

well look.. make long story short, i just want a basic enter key event handler, i know it works perfectly with submit buttons cus you don't need to program anything at all, its default. but my button is type="button" .... so when you press enter nothing happens... how do i trigger my button by pressing enter?

回答1:

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
    }
}


回答2:

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
    }
}


回答3:

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
    }
}