outside the form so that it is not sent when the user ent...">

Javascript keypress enter key

I have an input field <input type="text" name="input" />outside the form so that it is not sent when the user enters. I want to know when the user presses input without sending, so that I can run some JavaScript. I want this to work in all major browsers (I still didn't care about IE) and be valid JavaScript.

FYI: jQuery is an option

+5
source share
2 answers

I will not use jQuery, and this will work in IE <9 too. Using jQuery or other frameworks, you can have simpler ways to connect event listeners.

var input = document.getElementsByName("input")[0];
if (input.addEventListener)
    input.addEventListener("keypress", function(e) {
        if (e.keyCode === 13) {
            // do stuff
            e.preventDefault();
        }
    }, false);
else if (input.attachEvent)
    input.attachEvent("onkeypress", function(e) {
        if (e.keyCode === 13) {
            // do stuff
            return e.returnValue = false;
        }
    });
+7
source
$("input[name='input']").keypress(function(e) {
    //13 maps to the enter key
    if (e.keyCode == 13) {
        doSomeAwesomeJavascript();
    }
})


function doSomeAwestomeJavascript() {
    //Awesome js happening here.
}
+5
source

All Articles