I have multiple submit button on the page. What I want is if user presses enter on any input field it should click the related submit button. I tried the way below but it even couldnt catch the key press on the input fields.
Thanks in advance,
$('* input').keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$(this).closest('input[type=submit]').click();
}
});
I have multiple submit button on the page. What I want is if user presses enter on any input field it should click the related submit button. I tried the way below but it even couldnt catch the key press on the input fields.
Thanks in advance,
$('* input').keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$(this).closest('input[type=submit]').click();
}
});
Share
Improve this question
asked Oct 1, 2011 at 8:50
Barış VelioğluBarış Velioğlu
5,84715 gold badges62 silver badges106 bronze badges
5
-
3
Why do you want to catch the
Enter
key? If it is pressed anywhere in the input field, excepttextarea
s, it will submit that particular form. – Shef Commented Oct 1, 2011 at 8:52 - As long as it's in a form element (which I'm guessing it is, since you're using a submit button), it will get submitted on its own if enter is hit in an input field. Try this – Some Guy Commented Oct 1, 2011 at 10:03
- Gotta agree with Shef, you will always sent the apropriate submit if your HTML/Form Structure is correct - there shall be no submit/inputs without a form! – Sam Commented Oct 1, 2011 at 10:04
- @Shef I have one parent form and multiple submit button. So here is the problem. – Barış Velioğlu Commented Oct 1, 2011 at 10:39
- @Kaplan If you have one parent form, doesn't matter which submit button you click, there will be just one submitted form (the parent one). Thus, don't try to catch any enter key, just let the form be submitted if enter is pressed. – Shef Commented Oct 1, 2011 at 10:41
2 Answers
Reset to default 6Try this. .closest()
won't work unless the submit button is located upside in the DOM tree. Instead you could search for it inside the input's parentNode, or just submit the form (but you probably don't have a form element, because otherwise this would be the default behavior for the enter key).
$(document).ready(function() {
$('input[type="text"], input[type="password"]').keypress(function (event) {
if (event.keyCode == '13') { //jquery normalizes the keycode
event.preventDefault(); //avoids default action
$(this).parent().find('input[type="submit"]').trigger('click');
// or $(this).closest('form').submit();
}
});
});
It is not require javascript at all !
Enter key will call "implicit submission" by standards. When multiple input[type=submit] in form, the first one will implicitelly "clicked" by Enter. So, you should place default button to the first.
If you want to swap some buttons, use CSS rules for it.
Some interesting facts about buttons and Enter key is here.