Submit form with Enter key without submit button?

187,874

Solution 1

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

Solution 2

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();
    }
});

Solution 3

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.

Solution 4

@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;.

Share:
187,874
Alex
Author by

Alex

I'm still learning so I'm only here to ask questions :P

Updated on February 03, 2020

Comments

  • Alex
    Alex about 4 years

    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.

  • Ben Hull
    Ben Hull over 12 years
    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.
  • Martin Andersson
    Martin Andersson over 11 years
    This doesn't work for me, I have to set visibility: hidden; instead.
  • cwiggo
    cwiggo almost 11 years
    very helpful indeed! makes sense not to have submit form buttons everywhere
  • Dr. Ogden Wernstrom
    Dr. Ogden Wernstrom over 10 years
    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) { ...
  • MadsterMaddness
    MadsterMaddness over 9 years
    Don't forget to add the # in front of the input id!
  • Mai
    Mai about 9 years
    @MadsterMaddness Use the # only if we are specifying the ID of an element. From that answer, it specifies ALL the <input> elements.