Akshay Vasu
Akshay Vasu

Reputation: 445

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?

Upvotes: 0

Views: 729

Answers (3)

AnkitS
AnkitS

Reputation: 98

just put

<button type="button">Cancel</button>

for cancel and it will work.

Upvotes: 0

Sudhir Ojha
Sudhir Ojha

Reputation: 3305

Here is working code snippet your code is also working fine:

 <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">
<input type="submit" value="submit">
</form>

Upvotes: 0

Priyal Pithadiya
Priyal Pithadiya

Reputation: 889

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

Upvotes: 4

Related Questions