Implementation of JS Select All button

Simple functions that need to be implemented

function 1 When clicking the Select All button, let the buttons 1~4 be selected

  1. Click the Select All button
  2. Determine the selected state of the current select all button
  3. According to the selected state of the select all button, decide whether to let the buttons 1~4 be selected

function 2 When options 1~4 are all selected, let the select all button be selected

  1. Click one of the buttons in options 1~4
  2. Determine whether the currently selected 1~4 selected states are all selected
  3. If all are selected, select all button

1. The code of the html part

 <input type="checkbox" class="allBtn"> 全选
    <hr>
 <input type="checkbox" class="item"> 选项1 <br>
 <input type="checkbox" class="item"> 选项2 <br>
 <input type="checkbox" class="item"> 选项3 <br>
 <input type="checkbox" class="item"> 选项4 <br>

2. The code of the JavaScript part

function one

basic version

<script>
//第一步:获取元素:
var allBtn = document.querySelector('.allBtn')
// 获取class为allBtn的元素

var items = [...document.querySelectorAll('.item')]
//获取所有class为item的元素,并且输出为真数组

allBtn.onclick = function(){
      
      
       if(allBtn.checked === true){
      
      
       //选中1~4选项
          items.forEach(function(item){
      
      
             item.checked === true
         })
      } else{
      
      
      //取消选中1~4选项
        item.forEach(function(item){
      
      
        item.checked === flase
        })
}
</script>

Optimized version

<script>
//第一步:获取元素:
var allBtn = document.querySelector('.allBtn')
// 获取class为allBtn的元素

var items = [...document.querySelectorAll('.item')]
//获取所有class为item的元素,并且输出为真数组

allBtn.onclick = function(){
      
      
       if(allBtn.checked === true){
      
      
       //选中1~4选项
          items.forEach(function(item){
      
      
             item.checked === allBtn.checked
         })
      } else{
      
      
      //取消选中1~4选项
        item.forEach(function(item){
      
      
        item.checked === allBtn.checked
        })
}
</script>

final version

<script>
//第一步:获取元素:
var allBtn = document.querySelector('.allBtn')
// 获取class为allBtn的元素

var items = [...document.querySelectorAll('.item')]
//获取所有class为item的元素,并且输出为真数组

 allBtn.onclick = function () {
      
      
            items.forEach(function (item) {
      
      
                item.checked = allBtn.checked
            })
</script>

Function two

<script>
items.forEach(function (item) {
      
      
            item.onclick = function () {
      
      
                // 点击其中一个按钮的时候, 判断其他几个 的选中状态是否为 true; 如果都是true 那么选中全选; 否则不选中全选
                allBtn.checked = items.every(function (item) {
      
      
                    return item.checked
                })
            }
        })
</script>

Guess you like

Origin blog.csdn.net/weixin_48649246/article/details/127640145