Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Checkbox using JavaScript

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; 
                }   
            }
        }  
    } 
}
like image 303
Kervvv Avatar asked May 17 '16 21:05

Kervvv


People also ask

How do I toggle between checkboxes?

Given an HTML document having one checkbox and a group of checkboxes and the task is to toggle between them with the help of JavaScript. We can achieve this by using the event onChange() which is triggered whenever we check or uncheck the checkbox.

How check checkbox is checked or not in JavaScript?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

How do you check a checkbox in HTML?

The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.


3 Answers

It can be easier:

inputs[i].checked = !inputs[i].checked;
like image 196
Ali Seyfollahi Avatar answered Oct 27 '22 00:10

Ali Seyfollahi


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);
like image 20
Alex Stragies Avatar answered Oct 26 '22 23:10

Alex Stragies


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; 
         }   
    }
like image 21
IrkenInvader Avatar answered Oct 26 '22 23:10

IrkenInvader