Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent form submission on hitting Enter key for Text

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.

like image 730
AbuMariam Avatar asked May 21 '15 21:05

AbuMariam


People also ask

How do you stop re submitting a form after clicking back button?

You can check if the user clicked the back button, disable form if true. Another way is by storing a cookie which you check on page load, if it exists you can disable the form.


Video Answer


2 Answers

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>
like image 189
devkaoru Avatar answered Sep 30 '22 07:09

devkaoru


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;
     }
}
like image 25
user2755140 Avatar answered Sep 30 '22 07:09

user2755140