问题描述
我有两个复选框字段.我想使用Javascript来确保只勾选一个复选框.(例如,如果勾选了一个checkbox1,如果勾选了checkbox2,则checkbox1将取消选中)
I have two checkbox fields. Using Javascript, I would like to make sure only one checkbox can be ticked. (e.g if one checkbox1 is ticked, if checkbox2 is ticked, checkbox1 will untick)
<input name="fries" type="checkbox" disabled="disabled" id="opt1"/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled"/>
我还希望在其下方有一个单选按钮,如果单击该按钮,则希望取消选中两个复选框.
I would also like to have a radio button beneath, if this is clicked, I would like both checkboxes to be unticked.
<input type="radio" name="o1" id="hotdog" onchange="setFries();"/>
做到这一点的最好方法是编写一个函数,还是我可以使用onclick语句?
Would the best way to do this be by writing a function, or could I use onclick statements?
推荐答案
好吧,您应该使用单选按钮,但是有些人喜欢复选框的外观,因此应该注意这一点.我在您的输入中添加了一个通用类:
Well you should use radio buttons, but some people like the look of checkboxes, so this should take care of it. I've added a common class to your inputs:
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
演示: http://jsfiddle.net/5uUjj/
这篇关于取消选中一个复选框(如果另一个选中了javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!