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
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;
}
});
$("input[name='input']").keypress(function(e) {
//13 maps to the enter key
if (e.keyCode == 13) {
doSomeAwesomeJavascript();
}
})
function doSomeAwestomeJavascript() {
//Awesome js happening here.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With