Reputation: 127
I have a function that deals with checkboxes. I'm on a piece right now that I want to check if 3 variables are equal to each other (either true or false; it doesn't matter) and execute a command if that is so. I've tried a few different orientations and just can't get it to work.
function dump() {
var u = document.getElementById("dump").checked;
var x = document.getElementById("tractor").checked;
var y = document.getElementById("sweeper").checked;
var e = document.getElementsByClassName('dump');
var a = document.getElementsByClassName('tractor');
var b = document.getElementsByClassName('sweeper');
for (var i = 0; i < e.length; i++) {
/*This is the section*/
if (u==x && x==y)
e[i].style.display = "block";
a[i].style.display = "block";
b[i].style.display = "block";
/*End*/
if (u)
e[i].style.display = "block";
else
e[i].style.display = 'none';
if (x)
a[i].style.display = "block";
else
a[i].style.display = 'none';
if (y)
b[i].style.display = "block";
else
b[i].style.display = "none";
}
}
SOLVED
My real issue was I needed to move that statement to the end of the function. I also added brackets for good measure.
function dump() {
var u = document.getElementById("dump").checked;
var x = document.getElementById("tractor").checked;
var y = document.getElementById("sweeper").checked;
var e = document.getElementsByClassName('dump');
var a = document.getElementsByClassName('tractor');
var b = document.getElementsByClassName('sweeper');
for (var i = 0; i < e.length; i++) {
if (u){
e[i].style.display = "block";
}
else{
e[i].style.display = 'none';
}
if (x){
a[i].style.display = "block";
}
else{
a[i].style.display = 'none';
}
if (y){
b[i].style.display = "block";
}
else{
b[i].style.display = "none";
}
if (u==x && x==y){
e[i].style.display = "block";
a[i].style.display = "block";
b[i].style.display = "block";
}
}
}
Upvotes: 0
Views: 15683
Reputation: 3540
I think the problem is you have indenting, not braces:
/*This is the section*/
if (u==x && x==y){
e[i].style.display = "block";
a[i].style.display = "block";
b[i].style.display = "block";
}
/*End*/
The original code would only guard the "e" statement with the if statement and a & b would always execute.
But whatever this does is going to get possibly changed by the following block of if statements based on the individual values of u, x, and y.
Upvotes: 0
Reputation: 282043
You need braces:
if (u==x && x==y) {
e[i].style.display = "block";
a[i].style.display = "block";
b[i].style.display = "block";
}
Otherwise, the if
only attaches to the next statement,
e[i].style.display = "block";
The indentation is ignored.
Upvotes: 4
Reputation: 8973
Without curly braces your code will have following behaviour
if(u==x)
statement //if condition applies to only first statement
statement //will act as assignments
statement //
Hence you should curly braces here
if(ui==x && x==y){
e[i].style.display = "block";
a[i].style.display = "block";
b[i].style.display = "block";
}
Upvotes: 1