Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How to program a click counter?

I have tried before, but it doesn't work. Is it any wrongs of the code?

<script type ="text/javascript">
function count()
{
var x = 0;
x += 1;
document.getElementById( "counting" ).value = x;
}
</script>
</head>
<body>

<input type ="button" value = "Click" onclick = "count()"/><br><br>
<input id = "counting" type = "text" />

</body>
like image 843
Programme Newbie Avatar asked Nov 23 '09 12:11

Programme Newbie


People also ask

How do you count the number of times a button is clicked in Javascript?

Approach: First, we will create a HTML button and a paragraph element where we display the button click count. When the button is clicked, the JavaScript function called. We declare a count variable and initialize it to 0. When user clicks the button, the count value increased by 1 and display it on the screen.

How can count Click event in jQuery?

You can use jQuery's toggleClass function for that: $(" ... "). click(function() { $(this). toggleClass("someClass"); });


3 Answers

you need to move the line var x = 0; to somewhere outside of the function count in order for it to be in the global scope. This means that changes made to it by the function count will persist.

e.g.

var x = 0;
function count() {
    x += 1;
    document.getElementById( "counting" ).value = x;
}
like image 131
barkmadley Avatar answered Oct 04 '22 16:10

barkmadley


X appears to be declared as a local variable, so it's going to be reset to zero every time the function is called. Try moving "var x = 0;" outside the function (into global scope).

like image 32
BlueMonkMN Avatar answered Oct 04 '22 17:10

BlueMonkMN


You are initializing x to 0 every time the button is clicked. Try var x=0; outside the function.

like image 39
Soufiane Hassou Avatar answered Oct 04 '22 17:10

Soufiane Hassou