javascript confirm cancel still submits form

2019-09-01 06:44发布

问题:

I have the following sequence on a form page, first it runs through the captcha then it validates the email address and then asks if you are sure you want to unsubscribe.

Everything works perfectly except that clicking "Cancel" still submits the form. I can't use "onclick" in the submit button because it will bypass the captcha code. In my "if the email is true 'else'" statement I've tried both "return" and "return:false" but neither of them stop the form submission.

Thanks for your help.

<form action='<?php echo $_SERVER['PHP_SELF']; ?>' name="unsubscribe" method='post' onsubmit="return checkForm(this);"">

function checkForm(form) { 
var frm = document.unsubscribe;
 if(!form.captcha.value.match(/^\d{5}$/)) {
      alert('Please enter the CAPTCHA digits in the box provided'); 
        form.captcha.focus();           
        return false;
        }   
        if (validEmail(frm.Email.value) != true) {
                alert("Please enter a valid email address");
                frm.Email.focus();
                return false;
        }   
        if (validEmail(frm.Email.value) == true) {
                confirm('Are you sure you want to unsubscribe?');  
                return true;
        }
        else {          
            return false;   
    }
}   

function validEmail(email){
    var status = false; 
    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    if (email.search(emailRegEx) == -1) {
    status = false;
}
    else {
    status = true;
}
    return status;  
}   

回答1:

confirm returns a boolean - true if the user clicked "Ok", false if they clicked "Cancel", so simply return the result of the confirm call:

if (validEmail(frm.Email.value) == true) {
  return confirm('Are you sure you want to unsubscribe?');
}