Let’s take a look at the effect
Realize the principle of
checked
Properties: true and false, with the former selected and the latter unselected- The full checkbox state is the same as the parent of all check boxes, so the full checkbox is structurally the same as the parent of all check boxes
- Checkboxes cannot be checked as long as one full checkbox is not checked,
for
The loop implements all checkbox click events and checks whether all checkboxes are selected.
In the code
<! -- HTML structure -->
<div class="wrap">
<table>
<thead>
<tr>
<th>
<input type="checkbox" id="shopcar" />
</th>
<th>The shopping cart</th>
</tr>
</thead>
<tbody id="shopnames">
<tr>
<td>
<input type="checkbox" />
</td>
<td>Shoes and socks</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>Coat/cotton-padded coat</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>The trousers</td>
</tr>
<tr>
<td>
<input type="checkbox" />
</td>
<td>T-shirt</td>
</tr>
</tbody>
</table>
</div>
Copy the code
/* CSS style */
* {
padding: 0;
margin: 0;
}
/* Set panel properties */
.wrap {
width: 500px;
margin: 100px auto;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px solid #413f3f;
width: 500px;
}
th.td {
border: 1px solid #d0d0d0;
color: # 404060;
padding: 10px;
}
th {
background-color: #09c;
font: bold 24px Microsoft Yahei;
color: #fff;
}
td {
font: 20px Microsoft Yahei;
}
tbody tr {
background-color: #f0f0f0;
text-align: center;
}
tbody tr:hover {
cursor: pointer;
background-color: #fafafa;
}
Copy the code
/ * * / JS parts
// The first step is to achieve the full marquee box, select all; Click the full checkbox again, all are not checked
/* Get all selected cards */
var shopcar = document.getElementById("shopcar")
/* Get all check cards */
var shopnames = document.querySelectorAll("#shopnames input")
/* Iterate over all check cards to make their status consistent with the full check box ---- achieve full and deselect effect */
shopcar.onclick = function () {
for (var i = 0; i < shopnames.length; i++) {
// this.checked Current check box status, returns true if checked, false otherwise
shopnames[i].checked = this.checked; }}// In the second step, all checkboxes are unchecked if one of them is not checked
for (var j = 0; j < shopnames.length; j++) {
// The outer for loop adds click events for each checkbox
shopnames[j].onclick = function () {
// flag indicates the box status, which is true by default
var flag = true;
// Click the checkbox once to check that all checkboxes are selected
for (var i = 0; i < shopnames.length; i++) {
// Incomplete: one check box is not selected, execute if statement
if(! shopnames[i].checked) { flag =false; }}// Select all: if all check boxes are selected, the above if statement is not executed, directly use flag to define the true value of the pairshopcar.checked = flag; }}Copy the code