0

我在一页上有 2 个表格(在http://www.bumblebeezflorist.com/上将产品添加到您的购物篮)。你可以在这里看到小提琴:

http://jsfiddle.net/jeepstone/S5Fnn/

如果您有交付估算器,我想在有人单击结帐链接之前验证是否已输入某些内容。

因为我已经在我打算使用它的站点上拥有 jquery 验证库。到目前为止,我有:

if($('#cartForm').length > 0) {
    $('#proceedCheckout').on('click', function (event) {
        console.log('HSA');
        $('#changeCountry').validate({
            errorClass: 'alert-error'
        });
        event.preventDefault();
    });
}

如果您退出邮政编码字段,则验证可以正常工作,但如果您单击结帐按钮,则验证不会触发。我怎样才能做到这一点?

非常感谢

4

2 回答 2

1

你的代码:

if($('#cartForm').length > 0) {
    $('#proceedCheckout').on('click', function (event) {
        console.log('HSA');
        $('#changeCountry').validate({ // <-- move out of here
            errorClass: 'alert-error'
        });
        event.preventDefault();  // <-- should always be first in a function
    });
}

.validate()应该用于在 DOM 就绪的表单上初始化插件(及其选项)。由于您在每次点击时都重新初始化,因此您会看到意外的行为。

您还以不存在#changeCountry的地方为目标,因此我添加了与两个标签相对应的标签。idididform

每当您有两个表单并且一个表单的提交取决于另一个表单的验证状态时,请使用插件的.valid()方法来测试另一个表单。

尝试更多类似的东西:

$(document).ready(function () {

    // call .validate() to initialize the plugin
    $('#changeCountry').validate({
        errorClass: 'alert-error'
    });

    // on click, test the form using .valid()
    $('#proceedCheckout').on('click', function (event) {
        event.preventDefault();
        if ($('#changeCountry').valid()) {
            $('#cartForm').submit(); // passes validation
        } else {
            // failed validation
        }
    });

});

演示:http: //jsfiddle.net/B9d8A/

$('#changeCountry').validate()formwith上初始化 validate 插件id #changeCountry

$('#changeCountry').valid()以编程方式触发实际验证测试并返回一个true/false布尔值。

完整文档:

http://docs.jquery.com/Plugins/Validation

于 2013-02-07T17:16:48.643 回答
-1

为什么有条件地将点击事件添加到按钮?

我会在 click 事件中进行购物车测试,这样您就不会在 click 事件被正确分配给按钮时遇到任何问题。

$('#proceedCheckout').on('click', function (event) {
   console.log('HSA');
   if($('#cartForm').length > 0) {
     $('#changeCountry').validate({ errorClass: 'alert-error'  });
     event.preventDefault();
   }
});  
于 2013-02-07T16:17:57.953 回答