<script>
let SelectAll = document.querySelector('input')
let items = document.querySelectorAll('input:nth-child(n+2)')
// let a1 = SelectAll.checked
// console.log(a1)
SelectAll.onclick = function () {
let SelectAll_status = SelectAll.checked
console.log(SelectAll_status)
// console.log(items.length)
if (a1 = true) {
for (var i = 0;i < items.length;i++) {
items[i].setAttribute("checked", "true");
} } else {
for (var j = 0;j < items.length;j++) {
items[j].setAttribute("checked", "false");
let return1 = items[j].checked
}
console.log (return1)
}}
</script>
I use the If condition. But when I deselect the tick. Nothing works. Even the whole part of "Else" doesn't work.
At beginning, I used "items[i].checked= SelectAll.checked " , at console.log , "false" is given to items, but the tick toggle doesn't show. So,I need to use setAttribute. Then I need to use If conditions. And problems appear...
Updated Problem Solved : if (SelectAll_status === true) ,here must be "===" ,not "=" .
for Else , setAttribute is not working. I change it to removeAttribute .It works.
let SelectAll = document.querySelector('input')
let items = document.querySelectorAll('input:nth-child(n+2)')
SelectAll.onclick = function () {
let SelectAll_status = SelectAll.checked
console.log(SelectAll_status)
if (SelectAll_status === true) {
for (var i = 0;i < items.length;i++) {
items[i].setAttribute("checked", "true");
} } else {
for (var j = 0;j < items.length;j++) {
items[j].removeAttribute("checked");
}
}}
form {
border: 1px pink solid;
width: 200px;
background-image: linear-gradient(
rgb(255, 226, 255),
rgb(255, 250, 192)
);
color: rgb(121, 121, 121);
margin: 20px auto;
}
hr {
border: pink 1px solid;
}
<form action="">
<input type="checkbox" id="all" name="form1" />
<label for="opt">Select ALL</label>
<br />
<hr />
<input type="checkbox" id="opt1" name="form1" />
<label for="opt1">111111</label>
<br />
<input type="checkbox" id="opt2" name="form1" ckecked />
<label for="opt2">222222</label>
<br />
<input type="checkbox" id="opt3" name="form1" />
<label for="opt3">333333</label>
<br />
<input type="checkbox" id="opt4" name="form1" />
<label for="opt4">4444</label>
</form>
Aucun commentaire:
Enregistrer un commentaire