Prevent form submission (javascript)

I have a form with text input:

<form name="form1"> <cfinput type="text" name="text1" id="text1" onChange="someFunc();"> </form> 

I just want it to be in some cases. (First I will check for errors)

 <script> function someFunc() { if (1==2) { document.form1.submit(); } else { alert("Not submitting"); } </script> 

The problem is that, despite the fact that the warning works fine, the form form is still sent (there are no other offers besides this!).

Thanks so much if anyone can shed light on this.,

+7
javascript submit forms
source share
3 answers

There is a fundamental flaw in this approach. You are currently telling the form that when text1 changes, then call someFunc() . If true, use JavaScript to submit the form. If false, keep talking about your business. If you press enter in the text input, the form will still be submitted. If the submit button is clicked, the form is still submitted.

The main way to approach this:

 <form name="form1" onsubmit="return someFunc()"> <input type="text" name="text1" id="text1"> </form> 

When the message is sent, call someFunc() . This function should return either true or false. If it returns true, the form is submitted. If false, the form does nothing.

Now your JavaScript needs a little change:

 <script> function someFunc() { if (1==2) { return true; } else { alert("Not submitting"); return false; } } </script> 

You may have other functions that are called when the field changes, but they still will not handle the final presentation of the form. In fact, someFunc() may call other functions to perform a final check before returning true or false in the onsubmit event.

EDIT: Documentation on implicit form submission.

EDIT 2:

This code:

 $(document).ready(function(){ $("#text1").on('change', function(event){ event.preventDefault(); }); }); 

stops the default processing for the change event associated with this element. If you want to affect the submit event, you must do the following:

 $(document).ready(function(){ $("#form1").submit(function(event){ event.preventDefault(); }); }); 

Which will allow you to do something like this:

 $(document).ready(function(){ $("#form1").submit(function(event){ if ( $('#text1').val() !== "foo" ) { alert("Error"); event.preventDefault(); } }); }); 
+20
source share
  var form = document.getElementById("Your Form ID"); form.addEventListener("submit", function (e) { if ("Your Desired Conditions.") { e.preventDefault(); } }); 
+1
source share

use the following code, it will work fine

 <form onsubmit="return false;" > 
0
source share

All Articles