jquery - 选中复选框 2 时取消选中复选框 1

标签 jquery checkbox checked unchecked

我有一个非常简单的问题 - 我在想 - 但我自己无法解决。

我有两个复选框: 一个值为 Yes,另一个值为 No。

我需要某种脚本来帮助我在选中另一个时取消选中一个。所以如果我选中复选框否。 1 - 复选框编号2 自动取消选中 - 反之亦然。必须始终选中其中一个复选框(而且只有一个)。不 - 在这种情况下我不能使用单选按钮。

如果可以在 jQuery 中完成那就太好了 - 但任何帮助都可以:)

提前致谢

罗伯特

最佳答案

我能想到的最简单的方法是使用以下方法:

$('input:checkbox').change(
    function(){
        var group = this.name;
        $(this).siblings('input:checkbox[name="'+ group + '"][checked]').removeProp('checked');
    });

JS Fiddle demo .

但是有一些警告,上面使用 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/

相关文章:

javascript - 为什么在 Safari 中单击/聚焦子文本框时,父元素单击事件会自动触发?

jquery - CSS 并排 DIV - Dynatree 不水平填充

javascript - 如何在上一个动画结束后开始播放动画?

powershell - 选择其他复选框的Powershell复选框

checked - 如何以编程方式按下工具栏按钮?

jquery - 单击链接子元素时如何防止 IE 中出现 href,但仍执行绑定(bind)到 a 标记的方法?

html - 当我点击复选框时,只有一个 ul 标签在屏幕上可见

javascript - Foundation 复选框停止与 jQuery 配合使用

html - 从另一个页面单击单选按钮

javascript - 检查单选按钮是否已选中以及值是否匹配