Friedpanseller
Friedpanseller

Reputation: 699

How to increment a counter on click?

I have the following HTML:

<button id="ES" class="select" type="button">Select</button>
<h2>Total Units: <span id="totalselected"></span></h2>

and script:

var units=0;
document.getElementById('ES').onclick = function() {
    var units=units+2;
    document.getElementById("totalselected").innerHTML = units;
}​;​

I want that when the button is clicked, add + 2 to a counter.
It starts off at 0 and is displayed on the webpage.

When the button is clicked, the number jumps to two.
If it is clicked again, the number jumps to four.

Upvotes: 1

Views: 161

Answers (3)

Pulak
Pulak

Reputation: 1

<html>
<head>
<script>
 var c=0;
function test()
{
c=c+2;
document.getElementById("cnt").innerHTML=c;
}
</script>
</head>
<body>

<input type="button" value="Click" onClick="test()"/>
Count= <p id="cnt""></p>

</body>
</html>

Upvotes: -1

Jai
Jai

Reputation: 74738

change this:

var units=units+2;

to this:

units=units+2;  // remove the keyword var

As per your post:

I want that when the button is clicked, add + 2 to a counter. It starts off at 0 and is displayed on the webpage.

To start your values from 0 you can move your var unit = unit + 2 at the bottom:

var units=0;
document.getElementById('ES').onclick = function() {
   document.getElementById("totalselected").innerHTML = units;
   units=units+2;
};

Upvotes: 2

Black Sheep
Black Sheep

Reputation: 6694

Remove the second var on units

var units=0;
    document.getElementById('ES').onclick = function() {
    units=units+2; // here
    document.getElementById("totalselected").innerHTML = units;
};

DEMO

Upvotes: 6

Related Questions