0

请参考以下小提琴。

<form action="http://someurl.com/" id="test-form-1" method="post" name="test-form-1">
  <input class="test-domainurl" type="url"> <input class="test-order-button" type="submit" value="Continue to Order">
</form>
<form action="http://someurl.com/" id="test-form-2" method="post" name="test-form-2">
  <input class="test-domainurl" type="url"> <input class="test-order-button" type="submit" value="Continue to Order">
</form>


jQuery(document).ready(function($) {
    $(".test-order-button").click(function() {
        $("#test-form-1").validate({});
        $("#test-form-2").validate({});
        $(".test-domainurl").rules("add", {
            required: true
        });
    });
});

http://jsfiddle.net/vak87/

我不确定为什么只验证第一个表单?

有什么想法和建议吗?

谢谢

4

3 回答 3

2

您应该$(this)在 css 选择器中使用,并使用parent()andsiblings('.test-domainurl')来查找与每个按钮对应的元素。

jQuery(document).ready(function($) {
    $(".test-order-button").click(function() {
        $(this).parent().validate({});
        $(this).siblings('.test-domainurl').rules("add", {
            required: true
        });
    });
});

jsFiddle 示例

于 2013-08-06T15:21:12.690 回答
1

关于您对您的代码在 IE7 和 IE8 中不起作用的评论...

1)您绝对不需要包含.validate()click事件处理程序中。该.validate()方法只是插件的初始化,而不是测试方法。该.validate()方法只需要在 DOM 就绪时调用一次,并且任何后续调用都将被忽略。执行验证测试是因为点击是由插件自动捕获的。

2) 将.rules()方法附加到包含多个元素的 jQuery 对象时,必须将其包含在 jQuery.each()中。否则,该.rules()方法只会将规则分配给第一个匹配元素。

这是正确的方法...

jQuery(document).ready(function($) {

    $("#test-form-1").validate({});  // intialize plugin on first form

    $("#test-form-2").validate({});  // intialize plugin on second form

    $(".test-domainurl").each(function() {  // select applicable inputs
        $(this).rules("add", {              // apply the rule to each selected input
            required: true
        });
    });

});
于 2013-08-06T18:08:44.610 回答
0

我从未使用过 validate 插件,但我的猜测是选择器仅限于插件中的第一个匹配项。如果您单独添加规则,它似乎可以工作。

例子:

jQuery(document).ready(function($) {
    $(".test-order-button").click(function() {
        $("#test-form-1").validate({});
        $("#test-form-2").validate({});
        $(".test-domainurl").each(function(index, el) {
            $(el).rules("add", {
                required: true
            });
        });
    });
});
于 2013-08-06T15:11:50.673 回答