最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - javascript keypress enter key - Stack Overflow

programmeradmin3浏览0评论

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 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

Share Improve this question asked Oct 24, 2011 at 20:35 SamuelSamuel 1754 silver badges11 bronze badges 2
  • Possible duplicate: stackoverflow./questions/979662/… – Colin Brock Commented Oct 24, 2011 at 20:37
  • possible duplicate of Detect the Enter key in an text input field – JJJ Commented Oct 24, 2011 at 20:39
Add a ment  | 

2 Answers 2

Reset to default 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;
        }
    });
$("input[name='input']").keypress(function(e) {
    //13 maps to the enter key
    if (e.keyCode == 13) {
        doSomeAwesomeJavascript();
    }
})


function doSomeAwestomeJavascript() {
    //Awesome js happening here.
}
发布评论

评论列表(0)

  1. 暂无评论