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/