那么如何才能只允许用户选择一个复选框呢?
我知道单选按钮是“理想的”,但就我的目的而言......它不是。
我有一个字段,用户需要选择两个选项之一,但不能同时选择两个选项。问题是我需要我的用户也能够取消选择他们的选项,这就是单选按钮失败的地方,因为一旦选择了组,就必须选择一个选项。
我将通过 php 验证信息,但如果用户想要给出答案,我仍然希望将其限制为一个答案。
该片段将:
- 允许像单选按钮一样分组
- 像广播一样行动
- 允许取消选择全部
// the selector will match all input controls of type :checkbox
// and attach a click event handler
$("input:checkbox").on('click', function() {
// in the handler, 'this' refers to the box clicked on
var $box = $(this);
if ($box.is(":checked")) {
// the name of the box is retrieved using the .attr() method
// as it is assumed and expected to be immutable
var group = "input:checkbox[name='" + $box.attr("name") + "']";
// the checked state of the group/box on the other hand will change
// and the current value is retrieved using .prop() method
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<h3>Fruits</h3>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Kiwi</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Jackfruit</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Mango</label>
</div>
<div>
<h3>Animals</h3>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Tiger</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Sloth</label>
<label>
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Cheetah</label>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)