Reputation: 771
Hi i was im trying to make a jquery ajax submit form, and im currently trying to make restrictions for submiting a form. i want the user to press enter to submit a form and not press on a submit button, but only when the user is focusing on a textarea/input field it will submit when he/she presses enter!
i have attempted to make my own code and edit in it to see what works, and i have figured this code out, but it doesnt work quite well :(
$('.addformtextarea').focus(function() {
$(document).keyup(function(e){
switch (e.keyCode) {
case 13: //enter
//code to be
break;
}
});
.addformtextarea is the textarea to be focused on.
and does return false; behave the same as break; ? because i have a return false; right before break;
thanks :D
Upvotes: 0
Views: 1347
Reputation: 86433
Try this:
$('.addformtextarea').keyup(function(e){
switch (e.keyCode) {
case 13: //enter
//code to be
return false;
}
});
You don't need to worry about focus, because the keyup would only fire if the input has focus.
The break only breaks out of the switch, you need return false to prevent the automatic submit, if you are doing it with the code.
Upvotes: 0
Reputation: 298266
Try this:
$('textarea').keydown(function(e) {
if (e.which == 13) {
alert('You pressed enter');
// $('your_form').submit();
}
});
If the user is typing in the textarea, then wouldn't it be focused? I don't really like redundancy.
Demo: http://jsfiddle.net/cjTu9/4/
Upvotes: 1
Reputation: 166001
You would probably be better off binding to the keyup
event of the input:
$(".addformtextarea").keyup(function(e) {
switch (e.which) {
case 13: //enter
//code to be
break;
}
});
Notice that I've used which
instead of keyCode
. That's just because jQuery normalizes the event object to remove any cross-browser inconsistencies.
The problem with your current code is that once the focus
event is fired, the keyup
event is bound to the document
and will trigger whether the element has focus or not.
Upvotes: 1