ChatGPT解决这个技术问题 Extra ChatGPT

Prevent users from submitting a form by hitting Enter

I have a survey on a website, and there seems to be some issues with the users hitting enter (I don't know why) and accidentally submitting the survey (form) without clicking the submit button. Is there a way to prevent this?

I'm using HTML, PHP 5.2.9, and jQuery on the survey.

Don't use form tags and do custom ajax request :) But sure, you can go ahead with the key-listening and prevention approach, that's what I'd do..
I just don't use the form tags because I prefer to process forms through ajax requests by non-conventional ways (i.e: submitting some fields as their focus are dropped, etc). You can also make a special listener to catch Enter key and process it only if you want to do it.

P
Peter Mortensen

You can use a method such as

$(document).ready(function() {
  $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});

In reading the comments on the original post, to make it more usable and allow people to press Enter if they have completed all the fields:

function validationFunction() {
  $('input').each(function() {
    ...

  }
  if(good) {
    return true;
  }
  return false;
}

$(document).ready(function() {
  $(window).keydown(function(event){
    if( (event.keyCode == 13) && (validationFunction() == false) ) {
      event.preventDefault();
      return false;
    }
  });
});

I'm currently just looking for a quick fix, and don't have time to implement validation items. I appreciate everyone's answers, but this is the one i'm going to go with in the mean time. thank you.
This method is unideal because it prevents the user from submitting the form by pressing enter while focused on the submit button. The best solution would be that of BalusC below, where enter is interrupted only while still focused on the form inputs.
I've seen situations (Internet Explorer only) where you need to bind to keydown on the document instead of the window for this to work.
You might want to add && !$(document.activeElement).is('textarea') to the condition, or else newlines inside a textarea are blocked (in IE at least).
This works for me. But this also prevent to add break line in textarea.
B
BalusC

Disallow enter key anywhere

If you don't have a <textarea> in your form, then just add the following to your <form>:

<form ... onkeydown="return event.key != 'Enter';">

Or with jQuery:

$(document).on("keydown", "form", function(event) { 
    return event.key != "Enter";
});

This will cause that every key press inside the form will be checked on the key. If it is not Enter, then it will return true and anything continue as usual. If it is Enter, then it will return false and anything will stop immediately, so the form won't be submitted.

The keydown event is preferred over keyup as the keyup is too late to block form submit. Historically there was also the keypress, but this is deprecated, as is the KeyboardEvent.keyCode. You should use KeyboardEvent.key instead which returns the name of the key being pressed. When Enter is checked, then this would check 13 (normal enter) as well as 108 (numpad enter).

Note that $(window) as suggested in some other answers instead of $(document) doesn't work for keydown/keyup in IE<=8, so that's not a good choice if you're like to cover those poor users as well.

Allow enter key on textareas only

If you have a <textarea> in your form (which of course should accept the Enter key), then add the keydown handler to every individual input element which isn't a <textarea>.

<input ... onkeydown="return event.key != 'Enter';">
<select ... onkeydown="return event.key != 'Enter';">
...

To reduce boilerplate, this is better to be done with jQuery:

$(document).on("keydown", ":input:not(textarea)", function(event) {
    return event.key != "Enter";
});

If you have other event handler functions attached on those input elements, which you'd also like to invoke on enter key for some reason, then only prevent event's default behavior instead of returning false, so it can properly propagate to other handlers.

$(document).on("keydown", ":input:not(textarea)", function(event) {
    if (event.key == "Enter") {
        event.preventDefault();
    }
});

Allow enter key on textareas and submit buttons only

If you'd like to allow enter key on submit buttons <input|button type="submit"> too, then you can always refine the selector as below.

$(document).on("keydown", ":input:not(textarea):not(:submit)", function(event) {
    // ...
});

Note that input[type=text] as suggested in some other answers doesn't cover those HTML5 non-text inputs, so that's not a good selector.


This one should be the good answer since it also deals with form including textarea and better explain event propagation
This prevents enter key from working on any input other than textarea. It's not a good solution
This should be the correct answer since it does not interfere with other enter key listeners. Ones like Bootstrap tags input: bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples
I chose this solution because it wasn't even a full line of code I had to add. All things held equal, shorter answers are better.
Below is a much easier solution: stackoverflow.com/questions/895171/…
D
Daniel Trebbien

Section 4.10.22.2 Implicit submission of the W3C HTML5 spec says:

A form element's default button is the first submit button in tree order whose form owner is that form element. If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button. Note: Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)

Therefore, a standards-compliant way to disable any implicit submission of the form is to place a disabled submit button as the first submit button in the form:

<form action="...">
  <!-- Prevent implicit submission of the form -->
  <button type="submit" disabled style="display: none" aria-hidden="true"></button>

  <!-- ... -->

  <button type="submit">Submit</button>
</form>

One nice feature of this approach is that it works without JavaScript; whether or not JavaScript is enabled, a standards-conforming web browser is required to prevent implicit form submission.


On one hand it's simple and prevents all the pitfalls suggested by the accepted answers. On the other hand, it feels like a slight exploitation of the standard. Kudos for including aria-* attribute. I would love to hear more feedback on this.
Also works as <input type="submit" disabled style="display: none" aria-hidden="true" /> and you can reduce the size of your page by a few chars. :-P
IE 11 submits anyway.
This does not work on Safari, other browsers seem okay
Safari is the new IE.
U
Upgradingdave

I had to catch all three events related to pressing keys in order to prevent the form from being submitted:

    var preventSubmit = function(event) {
        if(event.keyCode == 13) {
            console.log("caught ya!");
            event.preventDefault();
            //event.stopPropagation();
            return false;
        }
    }
    $("#search").keypress(preventSubmit);
    $("#search").keydown(preventSubmit);
    $("#search").keyup(preventSubmit);

You can combine all the above into a nice compact version:

    $('#search').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13) { e.preventDefault(); }
    });

You could either chain the last 3 selectors or bind multiple events with one method like so $("#search").bind('keypress keyup keydown',preventSubmit);
Because in an ASP.NET web form everything has to be nested in a <form> tag, the enter key will submit the form... This solution disabled the enter key and fixed the problem though, thanks @Dave! Then I enabled the enter key for certain fields by id.
@Upgradingdave How are you able to write "log()" instead of "console.log()"?
@radbyx ... good catch, it should be console.log, I updated my answer.
Note that with keypress keyup keydown you trigger any code in the if condition twice.
P
Peter Mortensen

If you use a script to do the actual submit, then you can add "return false" line to the onsubmit handler like this:

<form onsubmit="return false;">

Calling submit() on the form from JavaScript will not trigger the event.


Works for me in Chrome, this will also disable submit buttons, which is fine if you want to trigger an onlick-event on the submit button itself. Ajax hint: Add your function call before the return and the user can still hit the enter key without submitting the form to the page.
Worked for me on Chrome, IE-11, and Firefox and was the simplest solution to implement. Disabling the enter key on whole sections of the page, as some answers do, seems too extreme and prone to bugs.
P
Peter Mortensen

Use:

$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.keyCode == 13) {
    e.preventDefault();
    return false;
  }
});

This solution works on all forms on a website (also on forms inserted with Ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.


I think the original answer e.which was fine; no need to change it to e.keyCode. Both return the value 13 for the enter key. See stackoverflow.com/a/4471635/292060 and stackoverflow.com/a/18184976/292060
This solution takes care of two solutions : 1.) Don't submit forms on enter 2.) Allows enter in the textareas
P
Peter Mortensen

Instead of preventing users from pressing Enter, which may seem unnatural, you can leave the form as is and add some extra client-side validation: When the survey is not finished the result is not sent to the server and the user gets a nice message telling what needs to be finished to complete the form. If you are using jQuery, try the Validation plugin:

http://docs.jquery.com/Plugins/Validation

This will require more work than catching the Enter button, but surely it will provide a richer user experience.


This sounds good but optional fields are problematic, the user may press enter by mistake and the form will be submitted. I do not see how you are going to know when the survey is not finished unless you put every field as required (no default choices, no blank fields allowed...)
P
Peter Mortensen

A nice simple little jQuery solution:

$("form").bind("keypress", function (e) {
    if (e.keyCode == 13) {
        return false;
    }
});

+1 I was looking for a jQuery alternative, instead of using normal JS like var key = event.keyCode || event.which; if (key == 13) return false;
technically this is still POJ just with a simpler jquery wrapper. the code that you've given is nearly the same thing.
E
Erics

A completely different approach:

The first

S
Stergios Zg.
$(document).on("keydown","form", function(event)
{
   node = event.target.nodeName.toLowerCase();
   type = $(event.target).prop('type').toLowerCase();

   if(node!='textarea' && type!='submit' && (event.keyCode == 13 || event.keyCode == 169))
   {
        event.preventDefault();
        return false;
    }
});

It works perfectly!


Out of interest, what keyboard key causes event keycode 169?
M
M Ali Imtiaz

I have use this Code to disable 'ENTER' key press on both input type [text] and input type [password], you can add other too like input type [email] or also can apply on your desired Input type.

$(document).on('keyup keypress', 'form input[type="text"] , input[type="password"]', function(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    });

W
Wenfang Du

If using Vue, use the following code to prevent users from submitting the form by hitting Enter:

<form @submit.prevent>...</form>

S
StackUnder

I had a similiar problem, where I had a grid with "ajax textfields" (Yii CGridView) and just one submit button. Everytime I did a search on a textfield and hit enter the form submitted. I had to do something with the button because it was the only common button between the views (MVC pattern). All I had to do was remove type="submit" and put onclick="document.forms[0].submit()


d
dubmojo

I think it's well covered with all the answers, but if you are using a button with some JavaScript validation code you could just set the form's onkeypress for Enter to call your submit as expected:

<form method="POST" action="..." onkeypress="if(event.keyCode == 13) mySubmitFunction(this); return false;">

The onkeypress JS could be whatever you need to do. There's no need for a larger, global change. This is especially true if you're not the one coding the app from scratch, and you've been brought into fix someone else's web site without tearing it apart and re-testing it.


I realize its a variant on Tom Hubbard's answer, which I +1'd because its actually what I did myself today before searching SO for other ideas.
b
bdoubleu

If you're using Alpine, you can use the following to prevent form submission by pressing Enter:

<div x-data>
  <form x-on:keydown.prevent.enter="">...</form>
</div>

Alternatively you can use the .window modifier to register the event listener on the root window object on the page instead of the element.

<form>
  <div x-data>
    <input x-on:keydown.window.prevent.enter="" type="text">
  </div>
</form>

P
Peter Mortensen

Something I have not seen answered here: when you tab through the elements on the page, pressing Enter when you get to the submit button will trigger the onsubmit handler on the form, but it will record the event as a MouseEvent. Here is my short solution to cover most bases:

This is not a jQuery-related answer

HTML

<form onsubmit="return false;" method=post>
  <input type="text" /><br />
  <input type="button" onclick="this.form.submit()" value="submit via mouse or keyboard" />
  <input type="button" onclick="submitMouseOnly(event)" value="submit via mouse only" />
</form>

JavaScript

window.submitMouseOnly=function(evt){
    let allow=(evt instanceof MouseEvent) && evt.x>0 && evt.y>0 && evt.screenX > 0 && evt.screenY > 0;
    if(allow)(evt.tagName=='FORM'?evt.target:evt.target.form).submit();
}

To find a working example: https://jsfiddle.net/nemesarial/6rhogva2/


W
Waqar Alamgir

Using Javascript (without checking any input field):

<script>
window.addEventListener('keydown', function(e) {
    if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        e.preventDefault();
        return false;
    }
}, true);
</script>

If someone wants to apply this on specific fields, for example input type text:

<script>
window.addEventListener('keydown', function(e) {
    if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        if (e.target.nodeName == 'INPUT' && e.target.type == 'text') {
            e.preventDefault();
            return false;
        }
    }
}, true);
</script>

This works well in my case.


L
Lars Gross

Go into your css and add that to it then will automatically block the submission of your formular as long as you have submit input if you no longer want it you can delete it or type activate and deactivate instead

 input:disabled {
        background: gainsboro;
      }
      input[value]:disabled {
        color: whitesmoke;
      }

D
David Dehghan

This disables enter key for all the forms on the page and does not prevent enter in textarea.

    // disable form submit with enter

    $('form input:not([type="submit"])').keydown((e) => {
        if (e.keyCode === 13) {
            e.preventDefault();
            return false;
        }
        return true;
    });