Toggle Checkbox using JavaScript

后端 未结 5 2123
栀梦
栀梦 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:35

    Another correct answer could be:

    inputs[i].checked = input.checked ? false : true;
    
    0 讨论(0)
  • 2021-02-06 06:36

    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; 
             }   
        }
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-02-06 06:51

    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;}})();
    
    0 讨论(0)
  • 2021-02-06 07:01

    It can be easier:

    inputs[i].checked = !inputs[i].checked;
    
    0 讨论(0)
提交回复
热议问题