2

我无法使用 jQuery validator.addMethod 来验证基于类名而不是名称的复选框。

看看这个,告诉我为什么脚本放在 html 内的脚本标签中时不起作用。

代码在这里:http: //jsbin.com/ecozih/2

如果将脚本移动到 JS bin 上的 JavaScript 窗口,它就可以工作。

如果有更简单的方法可以做到这一点,请告诉我。一个例子将不胜感激。

<html>
  <head>
<script src="hxxp://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="hxxp://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

  </head>
<body>
<script>
$.validator.addMethod('interests', function (value) {
return $('.interests:checked').size() > 0; }, 'Pick one or more');
var checkboxes = $('.interests');
var checkbox_names = $.map(checkboxes, function(e,i) { return $(e).attr("name")}).join(" ");
$("#subscribeForm").validate({
    groups: { checks: checkbox_names },
    errorPlacement: function(error, element) {
             if (element.attr("type") == "checkbox")
               error.insertAfter(checkboxes.last());
             else
               error.insertAfter(element);
}
});
</script>
<form name="subscribeForm" id="subscribeForm" method="post">
<input type="checkbox" class="interests" value="1" name="group[1357][1]" ><label>Bananas</label>
<input type="checkbox" class="interests" value="2" name="group[1357][2]"><label>Oranges</label>
<input type="checkbox" class="interests" value="4" name="group[1357][4]"><label>Apples</label><br />
<label for="checks" generated="true" class="error" style=""></label><br />
<input type="submit" />
</form>
  </body>

谢谢

4

1 回答 1

2

您忘记将 jQuery 代码包装在document.ready. 换句话说,您的 jQuery 正在尝试在元素构建之前选择元素。document.ready解决了这个问题。由于在form调用代码时 尚不存在,因此document.ready只有在 HTML DOM 准备好时才会触发。

jsFiddle 演示:http: //jsfiddle.net/TCHYJ/

和你的 jsBin:http: //jsbin.com/ecozih/4/edit

引用“如果你将脚本移到 JS bin 上的 JavaScript 窗口,它就可以工作。”

这是因为,jsBin 和 jsFiddle 的 JavaScript 窗格中的代码在被触发之前等待 DOM 加载,无论您是否使用document.ready

http://jsfiddle.net/TCHYJ/1/

http://jsbin.com/ecozih/6/edit

<script>
    $(document).ready(function() {

        $.validator.addMethod('interests', function(value) {
            return $('.interests:checked').size() > 0;
        }, 'Pick one or more');
        var checkboxes = $('.interests');
        var checkbox_names = $.map(checkboxes, function(e, i) {
            return $(e).attr("name")
        }).join(" ");

        $("#subscribeForm").validate({
            groups: {
                checks: checkbox_names
            },
            errorPlacement: function(error, element) {
                if (element.attr("type") == "checkbox") error.insertAfter(checkboxes.last());
                else error.insertAfter(element);
            }
        });

    });​
</script>
于 2012-11-14T14:42:16.960 回答