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

javascript - how do I call function when the user presses enter on the input - Stack Overflow

programmeradmin3浏览0评论

I want call function when the user presses enter on the input.

<input type='text' id='name'></input>

I found this code but it doesn't work.

$("#name").bind('keypress', function(e) {
if(e.which == 13) {
    alert('You pressed enter!');
}
});

I want call function when the user presses enter on the input.

<input type='text' id='name'></input>

I found this code but it doesn't work.

$("#name").bind('keypress', function(e) {
if(e.which == 13) {
    alert('You pressed enter!');
}
});
Share Improve this question asked Dec 4, 2013 at 0:15 user3063766user3063766 131 silver badge3 bronze badges 6
  • If your input is in a form make sure to prevent the default submit event, that may be the issue. – elclanrs Commented Dec 4, 2013 at 0:17
  • 3 It does work: jsfiddle/6CLw3 – Joren Commented Dec 4, 2013 at 0:19
  • try e.keyCode == 13 instead. I don't believe which is supported cross-browser. – broofa Commented Dec 4, 2013 at 0:19
  • The input element doesn't require a closing element. If you are using xhtml then use <input type='text' id='name' /> – user2417483 Commented Dec 4, 2013 at 0:19
  • @broofa - actually, event.which is normalized in jQuery, and works everywhere. – adeneo Commented Dec 4, 2013 at 0:28
 |  Show 1 more ment

3 Answers 3

Reset to default 4

Did you include the JQuery library? Your code appears to work fine in Chrome.

You could also do:

$("#name").keypress(function(e) {
    if(e.keyCode == 13) {
        alert('You pressed enter!');
    }
});

JSFiddle: http://jsfiddle/dMt55/

Non Jquery version:

document.getElementById('name').onkeypress = function(e) {
    if(e.keyCode == 13) {
        alert('You pressed enter!');
    }
}

Please try this;

<input type='text' id='name' />

$("#name").bind('keypress', function(event) {
                if (event.keyCode== 13) { //Enter
                  // your code 
                }
});

You can wire up your own custom event .Try this

HTML

<input type='text' id='name'></input>

Jquery

$('#name').bind("enterKey",function(e){
   //do stuff here
});
$('#name').keyup(function(e){
    if(e.keyCode == 13)
    {
        $(this).trigger("enterKey");
    }
});

http://jsfiddle/x7HVQ/

发布评论

评论列表(0)

  1. 暂无评论