我不知道爲什麼,這收到的反對票。單選按鈕的使用方式使得您可以有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