0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
galibo
  • 9
  • 5
  • `i` is your global variable when `onclick` function is called at that time `i` has a value which 4, so you need to pass div ID in `if` to check it, – Sumit Apr 19 '15 at 10:20
  • this will work: http://codepen.io/Legends/pen/yNBPdq.js – Legends Apr 19 '15 at 10:32
  • Thank you @juhana for pointing me in the right direction. I did search around before posting but couldn't find the relevant thread. Just in case anyone is intrested, here's the code that worked in the end: http://jsbin.com/lukifi/1/edit?js,output – galibo Apr 19 '15 at 11:35

0 Answers0