tags:

views:

63

answers:

2

Hi,

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));

If anyone can help - I'd be very grateful

+4  A: 

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.

Michal
I believe the keycode is 13 not 8?
James Westgate
You're right, 8 is backspace. Fixed.
Michal
You can't use `function` as a parameter name or variable name in JavaScript.
Tim Down
A: 

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){

    if(e){
        e = e
    } else {
        e = window.event
    }

    if(e.which){
    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.

Rapidz