2

I'm trying to have an error message/alert pop up when two checkboxes in the same row are selected. 我已经能够计算出复选框的总数,并且我知道如何计算当前选中了多少。我的每个复选框都有一个唯一的 ID。

<body>
<table id="tester">
<tr>
<td width="100" id="A1" ><label><input type="checkbox" name="A" value=1 id="A1" /> A1</label></td>
<td width="100" id="B1" ><label><input type="checkbox" name="B" value=1 id="B1" /> B1</label></td>
</tr>
<tr>
<td width="100" id="A2" ><label><input type="checkbox" name="A" value=1 id="A2" /> A2</label></td>
<td width="100" id="B2" ><label><input type="checkbox" name="B" value=1 id="B2" /> B2</label></td>
</tr>
</table>
    <input id="clickMe" type="button" value="clickme" onclick="test();" />
</body>

我的 jquery 技能非常基础。这是我一直用来计算框数和选中框数的代码。

    $(document).ready();
var len = $('input:checkbox').length;
console.log("There are "+len+" checkboxes");
var count2;
var test = function(){
    var count2 = $("[type='checkbox']:checked").length;
    console.log("There are "+count2+" checked checkboxes");
};

任何帮助都会很棒,谢谢!

4

3 回答 3

3

您可以使用.each()方法:

$('#tester tr').each(function(){
     var l = $(this).find('input[type=checkbox]:checked').length;
     if (l === 2) alert('2 checkboxes are checked');
});

.filter()方法:

$('#tester tr').has('input[type=checkbox]').filter(function() {
     return $(this).find('input[type=checkbox]:checked').length === 2;
}).addClass('error');

请注意,如果您想阻止表单提交,您应该在提交事件上验证表单元素,并且alert应该避免使用函数来提供更好的用户体验。

var $form = $('#tester'),
    $tr   = $form.has('input[type=checkbox]');

$tr.find('input[type=checkbox]').on('change', function() {
    var $tr = $(this).closest('tr'),
        checked = $tr.find('input[type=checkbox]:checked').length; 
    $tr.toggleClass('error', checked === 2);
});

$form.on('submit', function() {
    return $tr.filter('.error').length === 0;
}); 

jsFiddle.net 上的演示

于 2013-05-26T20:21:49.683 回答
1

单独处理每一行。

 // for each row
 $("#tester tr").each(function(){
     var count = $(this).find("input:checked").length;
     console.log("There are "+count+" checked checkboxes");
 });
于 2013-05-26T20:21:56.540 回答
0

怎么样

$(function () {
    $("#tester > tr").each(function () {
        if ($(this).children("input[type='checkbox']:checked").length > 1) {
            //more than one checkbox is checked
        }
    });
});
于 2013-05-26T20:23:11.000 回答