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

2

2 Answers 2

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;
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

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


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.