This is the code I'm working with:
var valueArray = new Array();
var i;
for(i=0; i<=3; i++) {
valueArray[i] = 0;
}
for(i=0; i<=3; i++) {
document.getElementById("div" + i).onclick=function() {
console.log(i);
/* The problem is that 'i' always has a value of 4. I don't know how to fix this. */
if(valueArray[i]===0) {
alert("hi");
}
};
}
<div id="div0" class="box">X</div>
<div id="div1" class="box">X</div>
<div id="div2" class="box">X</div>
<div id="div3" class="box">X</div>
Basically what should happen is that when I click on any div, then the alert box should open up and display "hi", if the corresponding value in the array is equal to zero.
So if I click on div0, and valueArray[0] equals 0, then the alert box should pop up.
Similarly when I click on div1 and valueArray[1] equals 0, or when I click on div2 and valueArray[2] equals 0, and so on.
The important thing is that
- this needs to happen when the user clicks on the div,
- the corresponding valueArray of the div should be equal to zero
- this needs to be done in HTML, CSS and JavaScript, because i don't understand jQuery and the other stuff.
As far as I can tell, what's happening is that the 'for' loop finishes doing it's thing, and then at the end of it all, the value of 'i' is stuck at four. And whenever I click a div, it uses i = 4. But I don't know how to fix this.