javascript confirm cancel still submits form

时光怂恿深爱的人放手 提交于 2019-12-12 03:25:39

问题


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?');
}


来源:https://stackoverflow.com/questions/28489222/javascript-confirm-cancel-still-submits-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!