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 i
E.g if you have submit button on form ,inorder to stop its propogation simply write event.preventDefault(); in the function which is called upon clicking submit button or enter button.
Use prevent default
Dojo Toolkit
dojo.connect(form, "onsubmit", function(evt) {
evt.preventDefault();
window.history.back();
});
jQuery
$('#form').submit(function (evt) {
evt.preventDefault();
window.history.back();
});
Vanilla JavaScript
if (element.addEventListener) {
element.addEventListener("submit", function(evt) {
evt.preventDefault();
window.history.back();
}, true);
}
else {
element.attachEvent('onsubmit', function(evt){
evt.preventDefault();
window.history.back();
});
}
Hemant and Vikram's answers didn't quite work for me outright in Chrome. The event.preventDefault(); script prevented the the page from submitting regardless of passing or failing the validation. Instead, I had to move the event.preventDefault(); into the if statement as follows:
if(check if your conditions are not satisfying)
{
event.preventDefault();
alert("validation failed false");
returnToPreviousPage();
return false;
}
alert("validations passed");
return true;
}
Thanks to Hemant and Vikram for putting me on the right track.
Just use a simple button
instead of a submit button. And call a JavaScript function to handle form submit:
<input type="button" name="submit" value="submit" onclick="submit_form();"/>
Function within a script
tag:
function submit_form() {
if (conditions) {
document.forms['myform'].submit();
}
else {
returnToPreviousPage();
}
}
You can also try window.history.forward(-1);
I would recommend not using onsubmit
and instead attaching an event in the script.
var submit = document.getElementById("submitButtonId");
if (submit.addEventListener) {
submit.addEventListener("click", returnToPreviousPage);
} else {
submit.attachEvent("onclick", returnToPreviousPage);
}
Then use preventDefault()
(or returnValue = false
for older browsers).
function returnToPreviousPage (e) {
e = e || window.event;
// validation code
// if invalid
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
Lets say you have a form similar to this
<form action="membersDeleteAllData.html" method="post">
<button type="submit" id="btnLoad" onclick="confirmAction(event);">ERASE ALL DATA</button>
</form>
Here is the javascript for the confirmAction function
<script type="text/javascript">
function confirmAction(e)
{
var confirmation = confirm("Are you sure about this ?") ;
if (!confirmation)
{
e.preventDefault() ;
returnToPreviousPage();
}
return confirmation ;
}
</script>
This one works on Firefox, Chrome, Internet Explorer(edge), Safari, etc.
If that is not the case let me know