5

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

Samuel
  • 175
  • 4
  • 11
  • Possible duplicate: http://stackoverflow.com/questions/979662/how-to-detect-pressing-enter-on-keyboard-using-jquery – Colin Brock Oct 24 '11 at 20:37
  • possible duplicate of [Detect the Enter key in an text input field](http://stackoverflow.com/questions/7060750/detect-the-enter-key-in-an-text-input-field) – JJJ Oct 24 '11 at 20:39

2 Answers2

8

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;
        }
    });
MaxArt
  • 22,200
  • 10
  • 82
  • 81
5
$("input[name='input']").keypress(function(e) {
    //13 maps to the enter key
    if (e.keyCode == 13) {
        doSomeAwesomeJavascript();
    }
})


function doSomeAwestomeJavascript() {
    //Awesome js happening here.
}
Marius Kjeldahl
  • 6,830
  • 3
  • 33
  • 37
Keith.Abramo
  • 6,952
  • 2
  • 32
  • 46