Take the 2-minute tour ×

I'd like to know how I can initiate a javacsript function when pressing the enter key. I'm trying to create a function called handleEnter(event, fn).

I want to use the function on an input field eg:

onkeypress="return handleEnter(event, update_field(this));
share|improve this question
What have you tried so far? –  Vivin Paliath Jun 28 '10 at 17:53
I think i've solved it. –  Rapidz Jun 30 '10 at 10:37

3 Answers 3

For your function called onkeypress, check the event's .keyCode or .which value, and see if it is equal to 13.

function handleEnter(e, func){
    if (e.keyCode == 13 || e.which == 13)
        //Enter was pressed, handle it here

IIRC, IE uses event.which, and Firefox will use e.keyCode to see which key was pressed.

share|improve this answer
I believe the keycode is 13 not 8? –  James Westgate Jun 28 '10 at 18:12
You're right, 8 is backspace. Fixed. –  Michal Jun 28 '10 at 18:28
You can't use function as a parameter name or variable name in JavaScript. –  Tim Down Jun 29 '10 at 9:36

I think I've solved it.

On the input field I've got:

<input onkeypress="return handleEnter(event, update_field, this, 'task');" type="text" />

For my function I've got:

function handleEnter(e, callback, obj, field){

        e = e
    } else {
        e = window.event

    var keycode = e.which
    } else {
    var keycode = e.keyCode

    if(keycode == 13) {
        var tstid = $(obj).parent().find('input[type=hidden]').val();
        callback.apply(this, [field, $(obj).val(), tstid ]);

and it seems to be working fine now.

share|improve this answer

You can try this shorthand

<input type=”text” onKeydown=”Javascript: if (event.keyCode==13) Search();”>

<input type=”button” value=”Search” onClick=”Search();”>

From http://www.techtamasha.com/call-javascript-function-on-pressing-enter-key/25

share|improve this answer

Your Answer


