Toggle Checkbox using JavaScript
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);
It can be easier:
inputs[i].checked = !inputs[i].checked;
Single equals is assignment, double/triple equals is for equality. You need to use double or triple equals in your if/else block.
if(inputs[i].checked == false) {
inputs[i].checked = true;
}
else {
if(inputs[i].checked == true) {
inputs[i].checked = false;
}
}