我一直在尝试一些代码,以便能够一次选中 1 个复选框,但我也希望能够同时在另一个组中一次选中 1 个复选框(它们一起工作)
这是我迄今为止尝试过的代码:
HTML
复选框组1
<div class="modal-body">
Status to change:
<br><br>
<label for=".checkboxSanction">Sanction Status
<input type="checkbox" name="statusbox" value="Sanction Status" class="checkboxSanction">
</label><br>
<label for=".checkboxPep">Pep Status
<input type="checkbox" name="statusbox" value="PEP Status" class="checkboxPep">
</label><br>
<label for=".checkboxUnderage">Underage Status
<input type="checkbox" name="statusbox" value="Underage Status" class="checkboxUnderage">
</label><br><br>
Change status to:
复选框组2
<label for=".checkboxInvestigating">Investigating
<input type="checkbox" name="valuebox" value="2" class="checkboxInvestigating">
</label></br>
<label for=".checkboxClosed">Closed
<input type="checkbox" name="valuebox" value="10" class="checkboxClosed">
</label>
</div>
jQuery
$("input:checkbox").on('click', function () {
var $box = $(this);
if ($box.is(":checked")) {
var group = "input:checkbox[name='" + $box.attr("name") + "']";
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
这里的问题是我一次只能选中 1 个复选框,并且这适用于所有复选框(如两组中一样) - 我希望能够为每组选中 1 个复选框。
有人知道如何解决这个问题吗?感谢您的帮助!
最佳答案
试试这个
$("input:checkbox").on('click', function() {
$("input:checkbox[name='"+$(this).attr('name')+"']").not($(this)).prop('checked', false);
});
与您的示例相同的概念,只是更简洁一点。
编辑:我刚刚正确检查了您的示例,它也工作正常,请参见此处
关于javascript - HTML 复选框每组一次选择一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34761631/