One way to stop form submission is to return false from your JavaScript function.
When the submit button is clicked, a validation function is called. I have a case in form validation. If that condition is met I call a function named returnToPreviousPage();
function returnToPreviousPage() { window.history.back(); }
I am using JavaScript and Dojo Toolkit.
Rather going back to the previous page, it submits the form. How can I abort this submission and return to the previous page?
Advertisement
Answer
You can use the return value of the function to prevent the form submission
<form name="myForm" onsubmit="return validateMyForm();">
and function like
<script type="text/javascript"> function validateMyForm() { if(check if your conditions are not satisfying) { alert("validation failed false"); returnToPreviousPage(); return false; } alert("validations passed"); return true; } </script>
In case of Chrome 27.0.1453.116 m if above code does not work, please set the event handler’s parameter’s returnValue field to false to get it to work.
Thanks Sam for sharing information.
EDIT :
Thanks to Vikram for his workaround for if validateMyForm() returns false:
<form onsubmit="event.preventDefault(); validateMyForm();">
where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()