0

I am new to javascript, but here it is. I am working on this page, and I want it to increase the variable for each question asked. I am confused as to why it is not working properly, I have tried different things for hours.

http://www.sprayfoamsys.com/cmsdev/index.php?page=rig-constructor

function clearVar(){
var sec1=0;
document.getElementById('sec1text').innerHTML = sec1;
var sec2=0;
document.getElementById('sec2text').innerHTML = sec2;
var sec3=0;
document.getElementById('sec3text').innerHTML = sec3;
}

function sec1Var(){
sec1++;
document.getElementById('sec1text').innerHTML = sec1;
alert(sec1);
}

function sec2Var(){
sec2++;
document.getElementById('sec2text').innerHTML = sec2;
alert(sec2);
}

function sec3Var(){
sec3++;
document.getElementById('sec3text').innerHTML = sec3;
alert(sec3);
}
Sameera Thilakasiri
  • 9,452
  • 10
  • 51
  • 86
  • I will add that the only reason I have the "document.getElementById('sec1text').innerHTML = sec1;" is to test my code –  Dec 19 '11 at 17:29

4 Answers4

0

This is because you have declared local variables. You need to declare global variables.

var sec1=0;
var sec2=0;
var sec3=0;

function clearVar(){
    sec1=0;
    sec2=0;
    sec3=0;
}

function sec1Var(){
    sec1++;
    alert(sec1);
}
Arnold Zokas
  • 8,306
  • 6
  • 50
  • 76
0

The console says:

Uncaught ReferenceError: sec1 is not defined

You have to actually declare sec1 etc:

var sec1 = 0,
    sec2 = 0,
    sec3 = 0;

function clearVar(){
    sec1 = 0; // update the declared variable to 0; don't declare it here
              // because it's then only accessible within this function

    // ... rest of code ...
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • I knew it had to be something simple, thanks for the help that solved my problem. –  Dec 19 '11 at 17:36
0

Variables in JavaScript are scoped to functions. Basically, this means that you cannot access a variable declared within a function from outside that function. As such, if you declare your variables in clearVar, you won't be able to access them from anywhere else. Just put them before the function declaration.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
  • Thanks for explaining the problem out, rather than just giving the answer. –  Dec 19 '11 at 17:43
0

Your counter variables must have a scope that allows them to survive from one invocation to the next so their value is maintained. You were using local variables that are destroyed and recreated each time your function is called.

Here's a working example of a cntr increasing on every button press: http://jsfiddle.net/jfriend00/DSfXb/

<button id="test">Click Me</button><br>
<div id="output">0</div>

// global variable
var cntr = 0;
document.getElementById("test").onclick = function() {
    cntr++;
    document.getElementById("output").innerHTML = cntr;
};
jfriend00
  • 683,504
  • 96
  • 985
  • 979