Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript keypress enter key

I have an input field <input type="text" name="input" /> outside of a form so that it is not submit when the user presses enter. I want to know when the user presses enter without submitting so that I can run some JavaScript. I want this to work in all major browsers (I don't care about IE though) and be valid JavaScript.

FYI: jQuery is an option

like image 936
Samuel Avatar asked Oct 24 '11 20:10

Samuel


2 Answers

I will not use jQuery and this is going to work in IE < 9 too. With jQuery or other frameworks you may have some simpler ways to attach 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;
        }
    });
like image 98
MaxArt Avatar answered Nov 05 '22 07:11

MaxArt


$("input[name='input']").keypress(function(e) {
    //13 maps to the enter key
    if (e.keyCode == 13) {
        doSomeAwesomeJavascript();
    }
})


function doSomeAwestomeJavascript() {
    //Awesome js happening here.
}
like image 44
Keith.Abramo Avatar answered Nov 05 '22 08:11

Keith.Abramo