user939222
user939222

Reputation: 17

Why are my clickCounts all adding on top of each other rather than counting separately?

<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Vote!</title>

<script type="text/javascript">
var x = 0;
function countClicks() {



x += 1
document.getElementById( "counting" ).innerHTML = x;

    ClickCount++;
    return true;
}

</script>

<script type="text/javascript">
var x = 0;
function countClicks1() {
x += 1
document.getElementById( "counting1" ).innerHTML = x;

    ClickCount++;
    return true;
}

</script>

<script type="text/javascript">
var x = 0;
function countClicks2() {



x += 1
document.getElementById( "counting2" ).innerHTML = x;

    ClickCount++;
    return true;
}

</script>

</head>
<body>

<div id="chart1">
<ul>
<li>
<img src="../Pictures/BWS + L.A +KUSH/Game.RED_Album_Cover.jpg" alt="red album"><br>
<input type="button" value="VOTE" name="clickOnce" onclick="return countClicks();" />
<div id="counting"></div>
</li>
<li>
<img src="../Pictures/BWS + L.A +KUSH/Game.RED_Album_Cover.jpg" alt="red album"><br>
<input type="button" value="VOTE" name="clickOnce" onclick="return countClicks1();" />
<div id="counting1"></div>
</li>
<li>
<img src="../Pictures/BWS + L.A +KUSH/Game.RED_Album_Cover.jpg" alt="red album"><br>
<input type="button" value="VOTE" name="clickOnce" onclick="return countClicks2();" />
<div id="counting2"></div>
</li>
</ul>
</div>

</body>

</html>

Upvotes: 0

Views: 47

Answers (2)

Tim B James
Tim B James

Reputation: 20364

var x is a global variable. Once it has been declared, then your functions will use the same variable. So in both countClicks and countClicks1 they are using the same variable.

Change the second to use var x2 = 0

Upvotes: 0

Itai Sagi
Itai Sagi

Reputation: 5615

ummm...

because x is a global variable and clickCount always using the same variable...

also, I'd suggest you to DRY your code, and make the function operate based on a parameter, you DON'T need 3 functions which all do exactly the same thing.

Upvotes: 1

Related Questions