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;
}
}
}
}
}
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.
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.
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.
It can be easier:
inputs[i].checked = !inputs[i].checked;
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);
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With