我有一個頁面上的兩個複選框,我希望他們作爲唯一的一個。例如,我選擇一個,另一個自動選擇,反之亦然。 我已經成功地一次選擇他們兩個,但我似乎無法找出一種方法來一次取消選擇。兩個複選框作爲一個
,什麼是困擾我的最,就是它可能是一個超級簡單的代碼行,我根本就沒有記住。
有沒有辦法做到這一點?
我有一個頁面上的兩個複選框,我希望他們作爲唯一的一個。例如,我選擇一個,另一個自動選擇,反之亦然。 我已經成功地一次選擇他們兩個,但我似乎無法找出一種方法來一次取消選擇。兩個複選框作爲一個
,什麼是困擾我的最,就是它可能是一個超級簡單的代碼行,我根本就沒有記住。
有沒有辦法做到這一點?
這是你在找什麼?
$(".test").change(function() {
$(".test").attr("checked", this.checked);
});
<input type='checkbox' class='test'>A<br />
<input type='checkbox' class='test'>B<br />
請添加一些關於此代碼爲何/如何幫助OP的解釋。這將有助於提供未來觀衆可以從中學習的答案。請參閱[這個元問題及其答案](http://meta.stackoverflow.com/q/256359/215552)瞭解更多信息。 –
此外,應該使用'prop('checked',this.checked)'布爾屬性值。 –
HTML:
<input type="checkbox" id="1" class="handleAsOne">
<input type="checkbox" id="2" class="handleAsOne">
的JavaScript(jQuery的):
$('.handleAsOne').on('change'){
$('.handleAsOne').prop('checked', false);
$(this).prop('checked', true);
}
如果我理解你的問題正確的您正在尋找這樣的事情。
這裏是純JavaScript的解決方案:
// Select all checkboxes using `.checkbox` class
var checkboxes = document.querySelectorAll('.checkbox');
// Loop through the checkboxes list
checkboxes.forEach(function (checkbox) {
// Then, add `change` event on each checkbox
checkbox.addEventListener('change', function(event) {
// When the change event fire,
// Loop through the checkboxes list and update the value
checkboxes.forEach(function (checkbox) {
checkbox.checked = event.target.checked;
});
});
});
<label><input type="checkbox" class="checkbox"> Item 1</label>
<br>
<label><input type="checkbox" class="checkbox"> Item 2</label>
$(document).ready(function() {
\t $('#check_one').change(function() {
\t $('#check_two').prop('checked', $('#check_one').prop('checked'));
});
\t $('#check_two').change(function() {
$('#check_one').prop('checked', $('#check_two').prop('checked'));
});
});
<form>
<label>Simple checkbox</label>
<input type="checkbox" id="check_one" />
<label>Complicated checkbox</label>
<input type="checkbox" id="check_two" />
</form>
假設你有不同的名稱,但協調工作的兩個複選框,該代碼會工作
發佈相關代碼,以便人們可以提供幫助。 – Joe
此外,檢查<標籤=「checkbox_id」 /> – Joe
你是如何設置呢?取消設置它們可能只是將「true」更改爲「false」的情況。 –