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(); } }); });
Adrian J. Moreno
source share