javascripthtmlformsform-submitconfirm

Even after clicking cancel the form gets submitted


I am doing a form submission, and I am displaying a confirmation box asking the user that if they really want to continue. But even if the user clicks on cancel, the form is still getting submitted.

 <form onsubmit="return confirm('If you enter the incorrect number, the search will still be conducted and charge you for the cost of the search. do you want to continue?.')" action="http:example.com/" id="customersearch" name="customersearch" role="form" method="post" accept-charset="utf-8" novalidate="novalidate">

How can I avoid this? Can anyone kindly tell me how to stop the form from getting submitted when the user clicks cancel?


Solution

  • @Akshay Vasu, try with below solution, you need to call onsubmit event of form

    function validateForm() {
       if(confirm('If you enter the incorrect number, the search will still be conducted and charge you for the cost of the search. do you want to continue?.'))
       {
          $("myform").submit();
          
       }
       else{
         alert("Invalid");
         return false;
       }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="myform" name="myForm" action="/action_page.php"
    onsubmit="return validateForm()" method="post">
    Name: <input type="text" name="fname">
    <input type="submit" value="Submit">
    </form>