html中checkbox多選框的全選

方法1 name
<body>
<script type="text/javascript" language="javascript">
function check(){
var oo=document.getElementsByName("pro"); //通過.getElementsByName()把name為“pro”的復(fù)選框定義成集合
for(var i=0;i<oo.length;i++){
oo[i].checked=document.getElementById("all").checked; //當(dāng)id為“all”的復(fù)選框被選中時(shí),讓集合中每一個(gè)對象都被選中
}
}
</script>
<input type="checkbox" id="all" onclick="check();" />全選
<input name="pro" type="checkbox" id="1" />蘋果
<input name="pro" type="checkbox" id="2" />梨
<input name="pro" type="checkbox" id="3" />香蕉
</body>

方法2 class
<!DOCTYPE html>
<html>
<head>
<title>全選復(fù)選框</title>
</head>
<body>
<h1>全選復(fù)選框</h1>
<input type="checkbox" id="selectAll"> 全選


<input type="checkbox" class="checkbox"> 選項(xiàng)1


<input type="checkbox" class="checkbox"> 選項(xiàng)2


<input type="checkbox" class="checkbox"> 選項(xiàng)3


<input type="checkbox" class="checkbox"> 選項(xiàng)4

<script>
const selectAllCheckbox = document.querySelector("#selectAll");
const checkboxes = document.querySelectorAll(".checkbox");

selectAllCheckbox.addEventListener("change", function() {
  const isChecked = this.checked;
  checkboxes.forEach((checkbox) => {
    checkbox.checked = isChecked;
  });
});

</script>

</body>
</html>

方法3使用jQuery實(shí)現(xiàn)

<!DOCTYPE html>
<html>
<head>
<title>全選復(fù)選框</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>全選復(fù)選框</h1>
<input type="checkbox" id="selectAll"> 全選


<input type="checkbox" class="checkbox"> 選項(xiàng)1


<input type="checkbox" class="checkbox"> 選項(xiàng)2


<input type="checkbox" class="checkbox"> 選項(xiàng)3


<input type="checkbox" class="checkbox"> 選項(xiàng)4

<script>
("#selectAll").on("change", function() { const isChecked = this.checked;(".checkbox").prop("checked", isChecked);
});
</script>

</body>
</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容