选中复选框 2 时取消选中复选框 1
我有一个非常简单的问题 - 我在想 - 但我自己无法解决。
我有两个复选框: 一个值为 Yes,另一个值为 No。
我需要某种脚本来帮助我在选中另一个时取消选中一个。所以如果我选中复选框否。 1 - 复选框编号2 自动取消选中 - 反之亦然。必须始终选中其中一个复选框(而且只有一个)。不 - 在这种情况下我不能使用单选按钮。
如果可以在 jQuery 中完成那就太好了 - 但任何帮助都可以:)
提前感谢
罗伯特
I have a pretty simple question - I'm thinking - but I cannot solve it myself.
I have two checkboxes:
One with value Yes, the other with value No.
I need a script of some sort to help me uncheck one when the other is checked. So if I check checkbox no. 1 - checkbox no. 2 automatically gets unchecked - and vice versa. One of the checkboxes - and only one - must always be checked. And no - i cannot use radio buttons in this case.
Would be great if it could be done i jQuery - but any help would do :)
Thanks in advance
Robert
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我能想到的最简单的方法是使用以下内容:
JS Fiddle demo。
但是有一些警告,上面使用了
removeProp()
,它仅限于 jQuery 1.6(大概是及以上版本)。在 1.6 之前,应该可以用removeAttr('checked')
代替。不过,请重新考虑使用
元素,这正是它们旨在处理的内容并与.
Edited following comment from Robert (in comments, below):
分配
change
事件处理程序的选择器是$('input:checkbox')
,它选择/应用于页面上的所有复选框。要将其仅应用于特定组中的复选框,您可以使用:
参考:
:checkbox< /代码>
。
change()
。siblings()
。removeProp()
。The easiest way that I could think of to do this is with the following:
JS Fiddle demo.
However there are some caveats, the above uses
removeProp()
, which is limited to jQuery 1.6 (and above, presumably). Prior to 1.6, it should be possible to substituteremoveAttr('checked')
instead.Please, though, reconsider using
<input type="radio" />
elements, this is precisely what they're designed to handle and work with.Edited following comment from Robert (in comments, below):
The selector that assigns the
change
event-handler is$('input:checkbox')
which selects/applies to all checkboxes on the page.To apply it to only those checkboxes in a particular group, you could use:
References:
:checkbox
.change()
.siblings()
.removeProp()
.编辑:现在应该可以了:-)
Edit: That should work now :-)
我就是这样做的
This is how I did it
这基本上表明,当选中 checkbox1 且用户尝试选中 checkbox2 时,checkbox1 将被取消选中。
This basically states that when checkbox1 is checked, and the user attempts to check checkbox2, checkbox1 will be unchecked.