How to call js function when you press enter

I would like to know how I can initiate the javacsript function when I press the enter key. I am trying to create a function called handleEnter(event, fn).

I want to use a function in an input field, for example:

onkeypress="return handleEnter(event, update_field(this));
+3
source share
3 answers

For your function called onkeypress, check the .keyCode or .which event for a value and see if it is 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.

+6
source

I think I decided.

In the input box I have:

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

For my function, I have:

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 now it works fine.

+1
source

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

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

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

0

Source: https://habr.com/ru/post/1752115/


All Articles