我有一个非常简单的问题 - 我在想 - 但我自己无法解决。
我有两个复选框: 一个值为 Yes,另一个值为 No。
我需要某种脚本来帮助我在选中另一个时取消选中一个。所以如果我选中复选框否。 1 - 复选框编号2 自动取消选中 - 反之亦然。必须始终选中其中一个复选框(而且只有一个)。不 - 在这种情况下我不能使用单选按钮。
如果可以在 jQuery 中完成那就太好了 - 但任何帮助都可以:)
提前致谢
罗伯特
最佳答案
我能想到的最简单的方法是使用以下方法:
$('input:checkbox').change(
function(){
var group = this.name;
$(this).siblings('input:checkbox[name="'+ group + '"][checked]').removeProp('checked');
});
但是有一些警告,上面使用 removeProp()
,仅限于 jQuery 1.6(大概是及以上版本)。 1.6之前,应该可以替换removeAttr('checked')
相反。
不过,请重新考虑使用 <input type="radio" />
元素,这正是它们旨在处理和使用的内容。
编辑以下来自 Robert 的评论(在下面的评论中):
I got this working as planned, BUT...in my form I have another group of checkboxes, and they get the restriction as well, although they have completely different names. But I need the user to be able to pick more than one of these checkboxes. It seems as though the script affects all checkbox groups. I actually thought that by putting in name="'+ group +'" one would limit the function to those checkboxes with a name starting with the word "group". But that seems not to be the case.
分配 change
的选择器事件处理程序是 $('input:checkbox')
它选择/应用于页面上的所有复选框。
要将其仅应用于特定组中的复选框,您可以使用:
$('input:checkbox[name="checkboxGroupName"]').change(
function(){
$(this).siblings().removeProp('checked');
});
引用文献:
关于jquery - 选中复选框 2 时取消选中复选框 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6417909/