Toggle Checkbox using JavaScript

后端 未结 5 2133
栀梦
栀梦 2021-02-06 06:07

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

5条回答
  •  醉酒成梦
    2021-02-06 06:44

    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 vars 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);
    

提交回复
热议问题