118

Possible Duplicate:
HTML: Submitting a form by pressing enter without a submit button

How can I submit a form with just the Enter key on a text input field, without having to add a submit button?

I remember this worked in the past, but I tested it now and the form doesn't get submitted unless there's a submit-type input field inside it.

Community
  • 1
  • 1
Alex
  • 60,472
  • 154
  • 401
  • 592

4 Answers4

212
$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});
timmah.faase
  • 2,189
  • 1
  • 13
  • 23
48

Change #form to your form's ID

$('#form input').keydown(function(e) {
    if (e.keyCode == 13) {
        $('#form').submit();
    }
});

Or alternatively

$('input').keydown(function(e) {
    if (e.keyCode == 13) {
        $(this).closest('form').submit();
    }
});
Jay Gilford
  • 15,052
  • 6
  • 34
  • 55
  • 8
    You can bind the keydown event on just the form, instead of binding the individual inputs: the keydown event will propagate up to the form. – Ben Hull Jan 24 '12 at 03:32
  • very helpful indeed! makes sense not to have submit form buttons everywhere – cwiggo Jun 18 '13 at 11:13
  • 2
    If your form had multiple input elements then slightly better would be to bind the handler to the form and filter for events from input elements like this: $('#form').on('keydown', 'input', function(e) { ... – Nine Tails Nov 19 '13 at 16:53
15

Jay Gilford's answer will work, but I think really the easiest way is to just slap a display: none; on a submit button in the form.

Brian Glaz
  • 14,239
  • 4
  • 32
  • 53
5

@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using display: none;.

FtDRbwLXw6
  • 25,206
  • 12
  • 61
  • 102