仅允许选中一个(批准/拒绝)复选框
更新:
$(document).ready(function () { $('#C1All').click(function () { debugger $('.col1').attr("checked", $('#C1All').attr("checked")); $('.col2').removeAttr("checked"); $('#C2All').removeAttr("checked"); }); $('#C2All').click(function () { debugger $('.col2').attr("checked", $('#C2All').attr("checked")); $('.col1').removeAttr("checked"); $('#C1All').removeAttr("checked"); }); $('.col1').each(function () { $(this).click(function () { var id = $(this).attr('id'); debugger var coresId = id.replace('C1', 'C2'); $('#' + coresId).removeAttr("checked"); $('#C1All').removeAttr("checked"); $('#C2All').removeAttr("checked"); }); }); $('.col2').each(function () { $(this).click(function () { var id = $(this).attr('id'); var coresId = id.replace('C2', 'C1'); debugger $('#' + coresId).removeAttr("checked"); $('#C1All').removeAttr("checked"); $('#C2All').removeAttr("checked"); }); }); });
我有两列(批准所有/拒绝所有)我如何限制用户只允许每个的一个复选框?
这是屏幕的输出:
我尝试过类似的东西,但没有奏效:
function SelectApproveAllCheckboxes(chk, selector) { $('#').find(selector + " input:checkbox").each(function () { $(this).prop("checked", $(chk).prop("checked")); }); } function SelectRejectAllCheckboxes(chk, selector) { $('#').find(selector + " input:checkbox").each(function () { $(this).prop("checked", $(chk).prop("checked")); }); }
根据您对问题的评论部分的问题的答案,这是一个有效的解决方案。 我使用了带静态控件的HTML表格; 但是你应该能够应用这些概念。
EDITED
因为在asp.net中,复选框嵌套在span标签中,所以使用这个jquery而不是前一个jquery。
$(document).ready(function () { $('#C1All').click(function () { $('.col1 > input').attr("checked", $('#C1All').attr("checked")); $('.col2 > input').removeAttr("checked"); $('#C2All').removeAttr("checked"); }); $('#C2All').click(function () { $('.col2 > input').attr("checked", $('#C2All').attr("checked")); $('.col1 > input').removeAttr("checked"); $('#C1All').removeAttr("checked"); }); $('.col1').each(function () { $(this).click(function () { var id = $("input", this).attr('id'); var coresId = id.replace('C1', 'C2'); $('#' + coresId).removeAttr("checked"); $('#C1All').removeAttr("checked"); $('#C2All').removeAttr("checked"); }); }); $('.col2').each(function () { $(this).click(function () { var id = $("input", this).attr('id'); var coresId = id.replace('C2', 'C1'); $('#' + coresId).removeAttr("checked"); $('#C1All').removeAttr("checked"); $('#C2All').removeAttr("checked"); }); }); });
不要使用复选框而是使用单选按钮,它们是为此而设计的。
我同意使用单选按钮。 您仍然可以选中“全选”复选框,并可以在选中时禁用单选按钮。
如果必须使用复选框,则只需覆盖默认的单击(检查)操作即可取消选中所有其他框。 它应该是非常基本的javascript,有或没有库。
试试这个:
$('input:checkbox').click(function(){ $('input:checked').removeAttr('checked'); $(this).attr('checked', 'checked'); });
这应该够了吧。
如果你使用单选按钮,你将无法获得全部选择function。
您可以将组中的所有复选框都放在同一个类中,并使用JQuery取消选中它们,同时选中或取消选中已单击的复选框:
$('.checkbox').click(function{ // save the original checked state of the one we're clicking: var checked = $(this).attr('checked'); $('.checkbox').attr('checked', false); // uncheck all of the boxes $(this).attr('checked', !checked); // invert the original state });
但更好的选择可能是使用“无以上”选项的单选按钮控件。 那样你就可以做validation了(那回答了问题吗?)