admin管理员组文章数量:1426946
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 believewhich
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
3 Answers
Reset to default 4Did 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/
本文标签: javascripthow do I call function when the user presses enter on the inputStack Overflow
版权声明:本文标题:javascript - how do I call function when the user presses enter on the input - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744624596a2616242.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论