JavaScript code that prevents form submission
P粉163465905
P粉163465905 2023-08-20 13:58:50
0
2
496
<p>One way to stop form submission is to return false from your JavaScript function. </p> <p>When the submit button is clicked, a validation function is called. I have a condition in form validation. If that condition is met, I call a function called <strong>returnToPreviousPage();</strong>. </p> <pre class="brush:php;toolbar:false;">function returnToPreviousPage() { window.history.back(); }</pre> <p>I'm using JavaScript and the Dojo Toolkit. </p> <p>Instead of returning to the previous page, it submits the form. How do I abort this submission and return to the previous page? </p>
P粉163465905
P粉163465905

reply all(2)
P粉457445858

使用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();
    });
}
P粉794851975

You can use the return value of the function to prevent the form from being submitted

<form name="myForm" onsubmit="return validateMyForm();">

And the function is as follows:

<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>

If the above code does not work in Chrome 27.0.1453.116 m, please set the event handler's parameter returnValue field to false .

Thanks Sam for sharing the information.

edit:

Thanks to Vikram for the solution, if validateMyForm() returns false:

<form onsubmit="event.preventDefault(); validateMyForm();">

Where validateMyForm() is a function that returns false when validation fails. The key point is to use the name event. We cannot use e.preventDefault()

for example
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!