An Phung
An Phung

Reputation: 409

Form without submit button on Enter

For form, without submit button, with 1 text input, do submit on Enter.

For form, without submit button, with more than 1 text input, do not submit on Enter.

Should both not submit on Enter?

<!-- This one do submit on Enter --> 
<form action="/">
  <input type="text" name="firstname" value="Mickey">
</form>

<!-- This one do not submit on Enter --> 
<form action="/">
  <input type="text" name="firstname" value="Mickey">
  <input type="text" name="lastname" value="Jerry">
</form>

Upvotes: 2

Views: 7614

Answers (2)

racz_gabor
racz_gabor

Reputation: 279

If the form has no submit button, then the implicit submission mechanism must do nothing if the form has more than one field that blocks implicit submission, and must submit the form element from the form element itself otherwise.

https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#implicit-submission

You can see here how the forms works with no submit button: https://www.tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/#no-submit-buttons

Upvotes: 4

thexpand
thexpand

Reputation: 641

Generally, it is not okay to suppress the Enter key as a way to submit a form. That being put away, you can achieve this kind of functionality, using the jQuery library for JavaScript (it will be easier for you to use).

Here is a modified version of your HTML. I have added a data attribute to identify those forms, which would not submit on Enter key:

<!-- This one WILL NOT submit, when the Enter key is pressed -->
<form action="/" data-disable-enter="1">
    <input type="text" name="firstname" value="Mickey">
</form>

<!-- This one WILL submit, when the Enter key is pressed
     If you want to suppress the Enter key submission, add the data attribute data-disable-enter="1" -->
<form action="/">
    <input type="text" name="firstname" value="Mickey">
    <input type="text" name="lastname" value="Jerry">
</form>

And here is the JavaScript code, using the jQuery library to suppress the Enter key form submission. An event listener is attached to listen for the keydown event on each of the form elements (input, select and textarea) in all forms that have the data attribute data-disable-enter="1". If the pressed key code is 13 (which means "Enter"), then we would prevent the default action, associated with the key pressing, which in our case is the form submission.

jQuery("form[data-disable-enter='1']").find("input, select, textarea").on("keydown", function(e){
    // 13 is the key code for the Enter key
    if(e.keyCode === 13){
        e.preventDefault();
    }
});

Upvotes: 0

Related Questions