cancel in confirm function submitting form in javascript

1.6k views Asked by At

Got a form that requires users to input an amount to donate. On clicking submit, a function is called and the function is meant to display the amount specified and prompt the user to confirm if the amount typed is the actual amount or not.

The Cancel option in the Confirm() keeps submitting the form instead of returning false.

function donationFormSend(){

    get_donation_amount = document.getElementById("get_donation_amt").value;

    if(get_donation_amount != ''){
        return confirm("You have specified "+get_donation_amount+" as the amount you wish to donate. \n\n Are you sure you want to proceed with the donation?");
    }
    else{
        alert("Amount must be specified to process your donation.");
        return false;   
    }

}    


<form method="post" action="">
<div>
      <div>Donation Amount:</div>
      <input name="amount" type="text" id="get_donation_amt" required="required" />
    </div>   
  <input name="donation_submit" type="submit" id="Submit" value="Proceed" onclick="return donationFormSend();" />
  </form>

Jsfiddle link

Would be pleased getting help with this.

3

There are 3 answers

0
James Levett On BEST ANSWER

I updated your jsfiddle so it's in the expected format (loading the js in the head) and returning the confirm result

return confirm('blah blah')

works perfectly well for me in FF! Just make sure you clear your cache and reload your page.

0
Bhaskara On
In your HTML use :   onclick="return  donationFormSend();"
In Your Javascript:  return confirm("Are you sure ....blah blah blah")
0
Thermatix On

A way to do do it might be:

form :

   <form id='test' method="post" action="">
    <div>
          <div>Donation Amount:</div>
          <input name="amount" type="text" id="get_donation_amt" required="required" />
     </div>   
      <input type="submit" value="submit" onClick="form_submit(this.value)">
    <input type="submit" value="cancel" onClick="form_submit(this.value)">
     </form>

javascript:

document.getElementById('test').addEventListener('submit',function (event) {
 if (event.preventDefault) { 
      event.preventDefault();
   } else {
      event.returnValue = false; 
   }
})

form_submit= function (submited_by) {

  if(submited_by == 'submit'){
    alert('Submited')
   }else if (submited_by == 'cancel'){
   alert('cancelled')  
  }

}  

I'd rather use a switch statement to make it expandable in the future but this should work.

Also I'm using jquery mostly because I'm not sure how to stop default action without it.

here's a JSFiddle with the code running.

EDIT: Updated to not use Jquery.

EDIT: well, I feel stupid now, realised it wasn't cancel button in a submit form but in a confirmation form.