2013-05-26 77 views
2

我想在选中同一行中的两个复选框时弹出错误消息/提醒。我已经能够统计复选框的总数,并且我知道如何计算当前有多少个复选框。我的每个复选框都有一个唯一的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"); 
}; 

任何帮助将是伟大的,谢谢!

回答

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; 
}); 

Demo on jsFiddle.net

+2

伟大的思想.... – cgTag

1

处理它自己的每一行。

// for each row 
$("#tester tr").each(function(){ 
    var count = $(this).find("input:checked").length; 
    console.log("There are "+count+" checked checkboxes"); 
}); 
0

如何

$(function() { 
    $("#tester > tr").each(function() { 
     if ($(this).children("input[type='checkbox']:checked").length > 1) { 
      //more than one checkbox is checked 
     } 
    }); 
}); 
相关问题