I had this working, but I didnt save and cannot replicate. I am trying to toggle checkboxes using if else
. What am I doing wrong.
What I thought would work
How about using an operator, that is defined to toggle booleans using 1 as second operand?
inputs[i].checked ^= 1;
This uses the XOR Compound assigment operator, and it toggles booleans because ¬A ≡ A ^ 1
.
It also doesn't require looking up inputs[i]
a second time.
2020 update:
You can also eliminate the for
loop and all those var
s by using the forEach function to iterate over the checkboxes, reducing your function body to:
document.querySelectorAll('input[type="checkbox"]').forEach(e => e.checked ^= 1);