14

I know this question has been asked before but I could not find a satisfactory answer for my situation. So I am asking again.

I have a simple form with 2 text boxes and a submit button. After the user enters text in either text box they should not be able to submit through the Enter key, only the submit button should allow them to submit. I thought trapping the enter keypress and returning false from the onChange event handler would do the trick but apparently not, this still causes a form submission...

function doNotSubmit(element) {

        alert("I told you not to, why did you do it?");
        return false;

}
</script>


<form id="myForm" action="MyBackEnd.aspx" method="post">

<table>
    <tbody>
    <tr>
        <td>
          Joe:  <input id="JoeText" type="text" onChange="doNotSubmit(this)">
        </td>
        <td>
          Schmoe:  <input id="SchmoeText" type="text" onChange="doNotSubmit(this)"  >
        </td>
    </tr>
    </tbody>
</table>

<input type=submit>

I tested on both Chrome and FF (latest versions).

Can you please show me how to prevent the form submission?

Thanks.

AbuMariam
  • 3,282
  • 13
  • 49
  • 82
  • 2
    possible duplicate of [Prevent Users from submitting form by hitting enter](http://stackoverflow.com/questions/895171/prevent-users-from-submitting-form-by-hitting-enter) – Dan May 21 '15 at 21:23
  • 1
    First, I think you want onkeypress or onkeydown instead of onchange. Second, where does `e` come from in your `doNotSubmit` function? – ray May 21 '15 at 21:25
  • @Dan That other question is not a true duplicate because it expressly names jQuery in the question and tags, whereas this question does not mention either. At a bare minimum, someone asking this question is open to non-jQuery solutions, and many (such as myself) would prefer such solutions. – cazort Nov 16 '21 at 17:49

6 Answers6

28

to piggy back on @Dasein's anwser you want to prevent the default behavior instead of stopping propagation ( i.e. returning false):

document.getElementById("myForm").onkeypress = function(e) {
  var key = e.charCode || e.keyCode || 0;     
  if (key == 13) {
    alert("I told you not to, why did you do it?");
    e.preventDefault();
  }
}
<form id="myForm" action="MyBackEnd.aspx" method="post">

<table>
    <tbody>
    <tr>
        <td>
          Joe:  <input id="JoeText" type="text">
        </td>
        <td>
          Schmoe:  <input id="SchmoeText" type="text" >
        </td>
    </tr>
    </tbody>
</table>

<input type=submit>
devkaoru
  • 1,142
  • 9
  • 7
  • @Dasein and devkaoru, I think your suggestion will work but right now when I insert the javascript as is, it makes my page loads give an error "document.getElementById(...) is null". Any idea why this is happening, I am sure the name of the form "myForm" is correct? – AbuMariam May 22 '15 at 13:56
  • 1
    you're script is most likely loading before your DOM is ready. use a on ready event to prevent this: http://stackoverflow.com/questions/9899372/pure-javascript-equivalent-to-jquerys-ready-how-to-call-a-function-when-the – devkaoru May 22 '15 at 15:25
  • I do not like this solution because it prevents the form from being submitted by pressing enter *on the submit button*. This could potentially make the form un-submittable by users who do not have access to a mouse, including people with a console browser, users with disabilities, etc. It's also unintuitive behavior even to users who have access to a mouse. – cazort Nov 15 '21 at 20:45
2

I think this should do:

document.getElementById("myInput").onkeypress = function(e) {
     var key = e.charCode || e.keyCode || 0;     
     if (key == 13) {
        alert("I told you not to, why did you do it?");
        return false;
     }
}
user2755140
  • 1,917
  • 4
  • 13
  • 16
  • No, sorry it does not work. The form still submits. But strangely I am not seeing the alert either. – AbuMariam May 21 '15 at 21:42
  • And yes I did change the parameter of getElementbyId to "JoeText". – AbuMariam May 21 '15 at 21:43
  • Curiously, it works for me as you can check here: http://jsfiddle.net/a70wuoo9/1/ – user2755140 May 21 '15 at 21:44
  • This solution also prevents *intentional* form submission when the user presses enter *while the submit button has the focus*, which is a major accessibility issue for users without a mouse, and may be a minor user experience issue for some users with a mouse. – cazort Nov 15 '21 at 21:16
2

For those using react:

    <form
      onSubmit={handleSubmit(onSubmit)}
      onKeyDown={e => {
        if (e.key === 'Enter') {
          // Keeps form from submiting on hitting enter
          e.preventDefault();
        }
      }}
    >
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 29 '22 at 18:50
0

If you include a submit button then the default form behavior is to submit on enter key. To prevent accidental submissions you could add a confirm dialog to the onsubmit event (form A). Another alternative is to replace the submit button with your own (form B). However, the user would then need to click the button to submit.

Run snippet to test (Tested in Chrome, Firefox, and IE 5-11)

<html>
<body>
Form A: This form submits on enter key    
<form action="handler.aspx" method="post" onsubmit="return confirm('submit form?')">
    <input type="text" >
    <input type="text" >
    <input type="submit">
</form>
<p>
Form B: This form submits only on button click<br>
<form action="hanlder.aspx" method="post" >
    <input type="text" >
    <input type="text" >
    <input type="button" value="submit" onclick="if (confirm('Submit form?')) document.forms[1].submit()">
</form>
    
</body>
</html>
Yogi
  • 6,241
  • 3
  • 24
  • 30
0

I am surprised no one has given a solution that achieves the desired effect of preventing accidental submission by hitting enter on a text field without also preventing intentional submission by hitting enter while the submit button has the focus.

To this end, I recommend:

function submitFunction(e)
{
    if(document.activeElement!=document.getElementById('submit')) e.preventDefault();
}

The lazy solution, which works but often results in code that is less extensible or more work to maintain, is to put this in the onsubmit attribute of the <form> element. Often a better solution is to use addEventListener to add the function as a listener to the form element:

document.getElementById('myForm').addEventListener('submit', submitFunction);

Regardless of which method you choose to invoke the function, in your HTML make sure to give an ID to the submit button:

<input type="submit" id="submit" />

I prefer this solution because it allows the expected behavior of allowing the user to submit the form by tabbing through the form and then pressing enter when the submit button is highlighted, and it also allows clicking on the submit button, because that element will have the focus in both these cases, but it prevents accidental submission because the submit element will not have the focus in these cases.

This is an improvement for accessibility which can be important for disabled users, users using a text-only console browser, users without a mouse, and can still be marked improvement for users with a mouse that is unreliable or inconvenient. It happens more than you might realize. Plus, some users just like being able to navigate this way, so not breaking this behavior is an improvement in user experience.

cazort
  • 516
  • 6
  • 19
0

How about below code snippet

 <form method="POST">
<div style="display: none;">
   <input type="submit" name="prevent-enter-submit" onclick="return false;">
  </div>
</form>
optimists
  • 191
  • 1
  • 7