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
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;
}
});