5

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>

3 Answers 3

8

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

document.getElementById( "counting" ).value = ++x; would also be a nice single line.
I wanted to keep it as close to his original code. Nice one liner.
1

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).

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.