我想在我的表单中使用javascript,以便在选中复选框后,该组中的其他复选框将被禁用,因此用户最多只能选择一个选项。
这是我的html表单:
<label>
<input type="checkbox" name="subscription[]" value="Sweets" id="subscription_1" />
Sweets
</label>
<label>
<input type="checkbox" name="subscription[]" value="Chocolate" id="subscription_2" />
Chocolate
</label>
<label>
<input type="checkbox" name="subscription[]" value="Fruit & Veg" id="subscription_3" />
Fruit & Veg
</label>
这是我正在尝试使用的JavaScript:
//Check check box
//Script for questions where you check one option or the other (locks other options out)
$(':checkbox').click(function(){
var $checkbox = $(this);
var isChecked = $checkbox.is(':checked')
//If no option is checked, the make all the options available to be selected
//Otherwise, one option must be checked so lock out all other options
if(isChecked)
$checkbox.subscription(":checkbox").attr("disabled", "disabled");
else
$checkbox.subscription(":checkbox").removeAttr("disabled");
});
有人可以解释我哪里出错吗?
答案 0 :(得分:1)
你几乎可以做你做的事情:
$(':checkbox').click(function(){
$(':checkbox').attr("disabled", "disabled");
$(this).removeAttr("disabled");
});
无需测试:禁用所有功能,然后启用单击功能。
请注意,此UI可能会让用户感到不安:这不是复选框的行为方式。例如,用户在第一次点击时锁定他们的选择会感到惊讶。
答案 1 :(得分:0)
这将有效:
var $checkboxes = $(':checkbox').click(function(){
$checkboxes.filter('[name="' +
this.name.replace(/\[/g,'\\[').replace(/\]/g,'\\]') +
'"]')
.not(this).prop('disabled',this.checked);
});
也就是说,保留对变量中所有复选框的引用(我称之为$checkboxes
)以保存每次都必须创建一个新的jQuery对象,然后当单击一个时你可以禁用或使用.filter()
方法重新启用所有其他名称,并使用.not
method排除当前名称。
另请注意(除非您使用旧版本的jQuery).prop()
method是设置禁用属性的合适方法。
演示:http://jsfiddle.net/rnbMB/2/
我可以建议,如果不是禁用其他复选框而只是取消选中它们对用户会更好吗?这样,一次最多只能检查一个,但用户在选择另一个之前不必首先取消选中当前的一个:
var $checkboxes = $(':checkbox').click(function(){
if (this.checked)
$checkboxes.filter('[name="' +
this.name.replace(/\[/g,'\\[').replace(/\]/g,'\\]') +
'"]')
.not(this).prop('checked',false);
});
演示:http://jsfiddle.net/rnbMB/3/
当然,无论哪种方式,您都需要将该代码放入文档就绪处理程序和/或所有复选框后出现的脚本块中。 (文档就绪处理程序可能是最好的,因为它会使$checkboxes
变量远离全局范围。)
答案 2 :(得分:-1)
尝试使用prop
代替attr
if(isChecked)
$checkbox.subscription(":checkbox").prop("disabled", true);
else
$checkbox.subscription(":checkbox").prop("disabled",false);