Article cover

全选文本框案例

需求:用户点击全选,则下面复选框全部选择,取消全选则全部取消

屏幕截图 2023-10-31 165819.png

代码实现

<!DOCTYPE html>

<html>

<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    table {
      border-collapse: collapse;
      border-spacing: 0;
      border: 1px solid #c0c0c0;
      width: 500px;
      margin: 100px auto;
      text-align: center;
    }

    th {
      background-color: #09c;
      font: bold 16px "微软雅黑";
      color: #fff;
      height: 24px;
    }

    td {
      border: 1px solid #d0d0d0;
      color: #404060;
      padding: 10px;
    }

    .allCheck {
      width: 80px;
    }
  </style>
</head>

<body>
  <table>
    <tr>
      <th class="allCheck">
        <input type="checkbox" name="" id="checkAll"> <span class="all">全选</span>
      </th>
      <th>商品</th>
      <th>商家</th>
      <th>价格</th>
    </tr>
    <tr>
      <td>
        <input type="checkbox" name="check" class="ck">
      </td>
      <td>小米手机</td>
      <td>小米</td>
      <td>¥1999</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" name="check" class="ck">
      </td>
      <td>小米净水器</td>
      <td>小米</td>
      <td>¥4999</td>
    </tr>
    <tr>
      <td>
        <input type="checkbox" name="check" class="ck">
      </td>
      <td>小米电视</td>
      <td>小米</td>
      <td>¥5999</td>
    </tr>
  </table>
  <script>
    //获取元素
    const checkAll = document.querySelector('#checkAll')
    //获取小复选框
    const cks = document.querySelectorAll('.ck')
    //点击大复选框 注册事件
    checkAll.addEventListener('click', function () {
      //获取选中状态
      //遍历所有小复选框
      for (let i = 0; i < cks.length; i++) {
        cks[i].checked = checkAll.checked
      }
    })
    for (let i = 0; i < cks.length; i++) {
      cks[i].addEventListener('click', function () {
        const num = document.querySelectorAll('.ck:checked').length
        if (num === cks.length) {
          checkAll.checked = true
        }
      })
    }
  </script>
</body>

</html>

Comments

Contents

404NotFound

Keyboard shortcuts

Ctrl/⌘+F
Open site search; press again while open for browser Find. Editing areas keep their original behavior.
Shift+D
Toggle appearance, except while editing text.
Esc
Close a theme menu or dismissible overlay.
↑ ↓
Select the previous or next quick action.
← →
Move between the toolbar icons.
Home End
Select the first or last quick action.
Enter Space
Run the selected action.
Tab
Leave the quick menu and continue through the page.

Hold Shift while right-clicking to keep the native menu.

Copy page link