Javascript - How to program a click counter?

I tried before, but this does not work. Are these some kind of code errors?

<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>
+5
source share
3 answers

you need to move the string var x = 0;somewhere outside the function countso that it is in the global scope. This means that the changes made to it by the function countwill be saved.

eg.

var x = 0;
function count() {
    x += 1;
    document.getElementById( "counting" ).value = x;
}
+8
source

X is represented as a local variable, so it will reset to zero with every function call. Try moving "var x = 0;" out of function (globally).

+1
source

x 0 , . var x=0; .

+1

All Articles