简体   繁体   English

javascript确认取消仍提交表格

[英]javascript confirm cancel still submits form

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. 我无法在“提交”按钮中使用“ onclick”,因为它将绕过验证码。 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. 在我的“如果电子邮件为真'else'”语句中,我尝试了“ return”和“ return:false”,但是它们都没有停止提交表单。

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;  
}   

confirm returns a boolean - true if the user clicked "Ok", false if they clicked "Cancel", so simply return the result of the confirm call: confirm返回一个布尔值 -如果用户单击“确定”,则返回 true ,如果单击“取消”,则返回false ,因此只需返回confirm调用的结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM