Home  >  Q&A  >  body text

JavaScript code that prevents form submission

<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粉163465905P粉163465905401 days ago466

reply all(2)I'll reply

  • P粉457445858

    P粉4574458582023-08-21 12:43:06

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

    reply
    0
  • P粉794851975

    P粉7948519752023-08-21 10:22:41

    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

    reply
    0
  • Cancelreply