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
Another correct answer could be:
inputs[i].checked = input.checked ? false : true;
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;
}
}
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);
I thought I would add to this since it led me to an answer I was seeking for checking all checkboxes with bookmarklet. Using the bitwise operator worked like a charm in IE 11 and Chrome. Haven't tried it in other browsers.
javascript:(function(){var chbxs=document.querySelectorAll('input');for(i in chbxs){chbxs[i].checked^=1;}})();
It can be easier:
inputs[i].checked = !inputs[i].checked;