我不知道为什么,这收到的反对票。单选按钮的使用方式使得您可以有0个或1个选项可供选择,如果需要选择0个或多个选项,则复选框列表是。但是如果你想撤销一个可选问题的单选按钮选择呢?
我通过在称为“数据检查”的单选按钮上创建另一个属性来解决此问题。
下面是执行:
$('input[type=radio]').on('click', function() {
var radioButton = $(this);
var radioButtonIsChecked = radioButton.attr('data-checked') == 'true';
// set 'checked' to the opposite of what it is
setCheckedProperty(radioButton, !radioButtonIsChecked);
// you will have to define your own getSiblingsAnswers function
// as they relate to your application
// but it will be something similar to radioButton.siblings()
var siblingAnswers = getSiblingAnswers(radioButton);
uncheckSiblingAnswers(siblingAnswers);
});
function uncheckSiblingAnswers(siblingAnswers) {
siblingAnswers.each(function() {
setCheckedProperty($(this), false);
});
}
function setCheckedProperty(radioButton, checked) {
radioButton.prop('checked', checked);
radioButton.attr('data-checked', checked);
}
在页面加载,数据核对属性设置为true或false,这取决于它是否已被选中。
$(document).ready(function() {
$('input[type=radio]').each(function() {
var radioButton = $(this);
var radioButtonIsChecked = radioButton.attr('checked') == 'checked';
setCheckedProperty(radioButton, radioButtonIsChecked);
});
});
你确定你不想要复选框吗?这似乎违背了单选按钮的正常使用。 –
不,因为有了复选框,您可以选择多个选项。我想选择0或1选项。这样用户可以撤消他们的选择,如果他们想要的话。 – socketman
我有一个可用的例子,向下滚动到我的答案 – Aaron