简体   繁体   中英

How do i call a js function on pressing enter key

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM