[英]checked radiobutton on checkbox change event
我們如何選中或取消選中復選框上的所有單選按鈕。如果復選框被選中,則所有單選按鈕也被選中,反之亦然..它不能正常工作
<input type="checkbox" id="Check" />SelectAll<br /><input type="radio"/>First<br />
<input type="radio"/>Second<br />
<input type="radio"/>Third<br />
<input type="radio"/>Fourth<br />
<input type="radio"/>Fifth</div>
<script>
var IsCheck = false;
$(document).ready(function () {
$("#Check").change(function () {
if (IsCheck == false) {
$("input[type=radio]").attr("checked", true);
IsCheck == true
}
else { $("input[type=radio]").attr("checked", false); IsCheck == false }
});
}); </script>
請注意,您只是比較操作數,而不是在此語句中分配給變量:
IsCheck == true
^------ REMOVE ONE = so it's an assignment
另外,請勿使用.attr("checked", true);
正確的形式是:
$("input[type=radio]").attr("checked", 'checked'); //checking for jQuery < 1.6
並取消選中:
$("input[type=radio]").removeAttr("checked"); //unchecking for jQuery < 1.6
如果您使用的是jQuery> 1.6,則可以將.prop()
方法與布爾值一起使用,這與您嘗試使用它的方式類似:
$("input[type=radio]").prop("checked", true); //checking for jQuery >= 1.6
$("input[type=radio]").prop("checked", false); //unchecking for jQuery >= 1.6
適用於jQuery 1.9或更高版本
$('input[type=radio]').prop("checked", true)
否則嘗試
$('input[type=radio]').attr('checked', 'checked');
嘗試這個
$(document).ready(function () {
$("#Check").change(function () {
$("input[type=radio]").attr("checked", $("#Check").is(":checked"));
});
});
對於您的問題,這可能是答案:
$("#Check").change(function () {
$("input:radio").prop("checked", this.checked);
});
演示: http : //jsfiddle.net/hungerpain/QSx29/
也就是說,單選按鈕不是執行此操作的最佳方法。 在語義上不正確。 您只能在一個組中選擇一個單選按鈕。 嘗試改用復選框。 嘗試更改您對此的標記:
<input type="checkbox" id="Check" />SelectAll
<br />
<input type="checkbox" />First
<br />
<input type="checkbox" />Second
<br />
<input type="checkbox" />Third
<br />
<input type="checkbox" />Fourth
<br />
<input type="checkbox" />Fifth</div>
並將JS代碼替換為:
$("#Check").change(function () {
$("input:checkbox").prop("checked", this.checked);
});
這是一個演示: http : //jsfiddle.net/hungerpain/QSx29/1/
你只需要這個
$("#Check").change(function () {
$("input[type=radio]").prop("checked", this.checked);
});
演示---->
http://jsfiddle.net/kLnyD/
嘗試這個
$("#Check").change(function () {
if ($(this).is(':checked')) {
$("input[type=radio]").prop("checked", true);
}
else { $("input[type=radio]").prop("checked", false); }
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.