html中checkbox多选框的全选

方法1 name
<body>
<script type="text/javascript" language="javascript">
function check(){
var oo=document.getElementsByName("pro"); //通过.getElementsByName()把name为“pro”的复选框定义成集合
for(var i=0;i<oo.length;i++){
oo[i].checked=document.getElementById("all").checked; //当id为“all”的复选框被选中时,让集合中每一个对象都被选中
}
}
</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>全选复选框</title>
</head>
<body>
<h1>全选复选框</h1>
<input type="checkbox" id="selectAll"> 全选


<input type="checkbox" class="checkbox"> 选项1


<input type="checkbox" class="checkbox"> 选项2


<input type="checkbox" class="checkbox"> 选项3


<input type="checkbox" class="checkbox"> 选项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实现

<!DOCTYPE html>
<html>
<head>
<title>全选复选框</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>全选复选框</h1>
<input type="checkbox" id="selectAll"> 全选


<input type="checkbox" class="checkbox"> 选项1


<input type="checkbox" class="checkbox"> 选项2


<input type="checkbox" class="checkbox"> 选项3


<input type="checkbox" class="checkbox"> 选项4

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

</body>
</html>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容