Reputation: 1211
I declare global var in script sitting in the head:
var numMonsters;
then i have somebody setup div with form that call js function also located in the head and there i assigning this var:
numMonsters = parseInt(document.getElementById("monsters").value , 10);
this is an element of that setup div.
later i replace divs with the display property : none/block
the new div contain my js game, there i want to use the value of that global var, but it won't stand even the simple conditional statement, the chrome debugger shows the correct value, and it seems to be defined but it's realy not:
board = new Array();
for (var i = 0; i < 10; i++) {
board[i] = new Array();
for (var j = 0; j < 10; j++) {
board[i][j] = new Array();
if ((i == 0) && (j == 0) && (numMonsters > 0)) {
board[i][j][1] = true;
board[i][j][2] = "red";
}
else if ((i == 9) && (j == 0) && (numMonsters > 1)) {
board[i][j][1] = true;
board[i][j][2] = "blue";
}
else if ((i == 9) && (j == 9) && (numMonsters > 2)) {
board[i][j][1] = true;
board[i][j][2] = "yellow";
}
else {
board[i][j][1] = false;
}
}
}
this var gets one of the {0,1,2,3} values if i considering only the i, j coordinates and then placing true it's doing the work so it's the numMonsters that wo'nt function, and as i mentioned the chrome debugger shows good value for it. it's droving me crazy, what am i doing wrong?! i also doing the same approach with other vars and they seems to work fine. thanks
Upvotes: 0
Views: 902
Reputation: 4880
That is working just fine. It is likely something else in your code causing a problem. Can you post some of the surrounding code?
HTML
Monsters: <input id="monsters" type="text" value="10"/>
Javascript
var numMonsters = parseInt(document.getElementById("monsters").value, 10);
if (numMonsters > 0) {
alert("Monsters win! Variable is a " + typeof numMonsters);
} else {
alert("Fail.");
}
EDIT: Your code does not work because the "monsters" element does not exist in the DOM at the point you are trying to reference it.
Upvotes: 2