开发者

Validating groups of checkboxes using jquery

If I have groups of checkboxes like so:

<input type="checkbox" name"checkboxes1" value="#value1">
<input type="checkbox" name"checkboxes1" value="value2">
<input type="checkbox" name"checkboxes1" value="#value3">

<input type="checkbox" name"checkboxes2" value="value1">
<input type="checkbox" name"checkboxes2" value="#value2">
<input type="checkbox" name"checkboxes2" value="#v开发者_JAVA百科alue3">

Is there an easy way in jquery to return a value of 1 for each group of checkboxes, if both of the following conditions apply:

  • All of the checkboxes in the group that start with a # in their value are checked
  • All of the checkboxes in the group that don't start with a # in their value are not checked

Note: the names of the checkboxes are dynamically generated, so there could be any number in a group, any number of groups and each group could have any name.

Thanks :)


You can select the attribute with [attr^=\#] pattern. So, you could code something like:

<html>
<head>
  <script src="./lib/jquery/jquery-1.3.2.js"></script>
  <script>
    var checkall = function() {

    var withHashAllChecked = true;
    var withoutHashAllChecked = true;

$("input.cb1:checkbox[value^=#]").each(function() {
    if (!this.checked) {
        withHashAllChecked = false;
    }
});


$("input.cb1:checkbox:not([value^=#])").each(function() {
    if (!this.checked) {
        withoutHashAllChecked = false;
    }
});

var result = withHashAllChecked && (!withoutHashAllChecked);
alert(result);

};

$(function() {
    $("input").click(checkall);
});
  </script>
</head>
<body>
<input class="cb1" type="checkbox" name"checkboxes1" value="#value1">#1</input>
<input class="cb1" type="checkbox" name"checkboxes1" value="value2">2</input>
<input class="cb1" type="checkbox" name"checkboxes1" value="#value3">#3</input>

<input class="cb2" type="checkbox" name"checkboxes2" value="value1">1</input>
<input class="cb2" type="checkbox" name"checkboxes2" value="#value2">#2</input>
<input class="cb2" type="checkbox" name"checkboxes2" value="#value3">#3</input>

</body>
</html>

EDIT

Updated Full working code. This is only checking checkboxes with class cb1, but just to give you an idea how to achieve. I must apologize that the original code has some problem that I didnt check it. Anyway, I try the above code and it should be fine (should you modify the jquery directory reference).


var checked = $('input:checkbox:checked[name=checkboxes1][value^=#]').length;
var notchecked = $('input:checkbox:not(:checked)[name=checkboxes1][value^=#]').length;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜