20

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:

function myForm() {
    var inputs = document.getElementsByTagName("input");
    for(var i = 0; i < inputs.length; i++) {
        if(inputs[i].type == "checkbox") { 
            if(inputs[i].checked = false) {
                inputs[i].checked = true; 
            } else {
                if(inputs[i].checked = true) {
                    inputs[i].checked = false; 
                }   
            }
        }  
    } 
}
8
  • why aren't you using toggle()? Commented May 17, 2016 at 21:38
  • 1
    Possible duplicate of Javascript toggle checkbox Commented May 17, 2016 at 21:42
  • @Harry thank you I will look at that function Commented May 17, 2016 at 21:57
  • @4castle Yes it should be input, sorry. When using your code, do I still need to put =true/false? Commented May 17, 2016 at 21:58
  • 2
    @Harry toggle() is jQuery correct? Commented May 17, 2016 at 22:18

5 Answers 5

84

It can be easier:

inputs[i].checked = !inputs[i].checked;
Sign up to request clarification or add additional context in comments.

Comments

45

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 in formal boolean math ¬A ≡ A ^ 1.
(Read as: "Not(¬) A is equivalent() to A XOR(^)ed with literal 1")

It also doesn't require using 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);

4 Comments

Whoa! Never seen that before. What is that operator ^=?
^ is the XOR operator; a ^ b is true if a and b have different values, or false otherwise. a ^= true (equivalent to a = a ^ true) evaluates to false if a is true and true if a is false.
While this "works", I don't think it's a good idea - using bitwise operators when not needed makes for less readable, more opaque code, as you can see by the first comment. It will confuse people. Readable code is more important than concise code, unless you're code golfing.
I disagree. Back in the day XOR was covered in the first week of CS. If "XOR 1" is "opaque" or "unreadable" to a non-beginner programmer, they should probably never go near any kind of performance, or security critical code.
7

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; 
         }   
    }

8 Comments

It is a good practice to always use ===/!== instead of ==/!= when comparing to Boolean, or to perform type coercion manually only when you need to.
In fact, the if statement inside the else statement is completely unnecessary. Just do inputs[i].checked = false; inside the else.
@Farside In this case they might as well use == to save bytes, because checked will always be a boolean. But yes, it is good practice.
I was actually planning on using triple equal as I wrote the opening sentence...not sure what happened.
Thank you. All of my checkboxes are toggling, except for the checkbox that initiates the toggling.
|
2

Another correct answer could be:

inputs[i].checked = input.checked ? false : true;

1 Comment

I like this one. The answers with the ^= operator work, but not all developers will understand it. This pattern is more widely known.
0

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;}})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.