在jQuery submit()函数中添加一个条件

时间:2014-02-18 14:04:26

标签: jquery submit

我有一个注册表格供多人注册。在我的submit()jQuery函数中,我想检查每个电子邮件地址是否与其对应的确认电子邮件地址匹配:

jQuery('[name="email_address\\[\\]"]').each(function(){
    var email = jQuery(this).val();
    var confirmation_email = jQuery(this).parents('.section').next('.section').children('input.confirm_email').val();
    if ( email != confirmation_email ) {
        alert("At least one email address does't match confirmation email address. Please check all email addresses");
        return false;
    }
});

问题是,return false只会中断each()函数的执行,而不会中断submit()函数的执行。如何从submit()函数中断each()函数执行?

1 个答案:

答案 0 :(得分:3)

each之外声明一些变量,如果电子邮件不相等,则为其分配false。然后返回此变量

var emailCorrect = true;

jQuery('[name="email_address\\[\\]"]').each(function(){
    var email = jQuery(this).val();
    var confirmation_email = jQuery(this)
                            .parents('.section')
                            .next('.section')
                            .children('input.confirm_email')
                            .val();
    if ( email != confirmation_email ) {
        alert("At least one email address does't match confirmation email address. Please check all email addresses");
        emailCorrect= false;
    }
});

return emailCorrect;