简体   繁体   中英

How can I detect the Enter key in Firefox?

I am able to successfully detect the Enter key in Internet Explorer 10, Chromium and Opera, but not in Firefox.

I have found a few pages on here, though they do not work in Firefox either. Am I doing something wrong, here?

TypeScript:

function HandleKeyPress(e) {
    var key = e.keyCode || e.which;

    if (key == 13) {
        // We got this.
        var textbox = <HTMLInputElement>document.getElementById("tbox");
        sayHello(textbox.value);
    }
}

Resulting JavaScript (identical):

function HandleKeyPress(e) {
    var key = e.keyCode || e.which;
    if(key == 13) {
        var textbox = document.getElementById("tbox");
        sayHello(textbox.value);
    }
}

HTML:

<input type="text" value="dfgdfgdfg" id="tbox" onkeypress="HandleKeyPress(event)" />

I can't use any external libraries, I have to do this in pure JavaScript (or a language that compiles to pure JS).


Update:


I just installed Firebug and in the Consolw pane I noticed (just after pressing the Enter jey on the textfield:

 http://localhost:1058/Default.cshtml?someValue=dfgdfgdfgkjkhj <p>You said: dfgdfgdfgkjkhj</p> 

See below for the pic:

在此处输入图片说明

Notice that the page itself has not updated the value of the response paragraph to what was entered in the textbox, but , Firebug does indeed say that it was successfully posted.

Now, since this code works on every other browser (IE, Chrome/Canary and <, Opera, Safari), my question is, maybe Firefox is detecting the key event, but the part that isn't working is after that?

You should change onkeypress to onkeydown as onkeypress only fires for printable characters in some implementations.

Your existing code should work with onkeydown .

try this:

<input type="text" value="dfgdfgdfg" id="tbox" onkeypress="HandleKeyPress(event)" />

And define the function HandleKeyPress as:

function HandleKeyPress(evt){
    var key = evt.which || evt.charCode || evt.keyCode || 0;

    if (key == 13) ...
}

You can accomplish by using jQuery like this

$(".input").keyup(function (e) {
    if (e.keyCode == 13) {
        // Whatever
    }
});

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