Skip to content Skip to sidebar Skip to footer

How Do I Use The Enter Key As An Event Handler (javascript)?

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 th

Solution 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:

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

Solution 2:

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

$(document).ready(function(){

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

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

Solution 3:

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

HTML:

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

Plain javascript:

functioninputKeyUp(e) {
    if (e.key === 'Enter') {
        // submit
    }
}

Post a Comment for "How Do I Use The Enter Key As An Event Handler (javascript)?"