0

I have a variable, I created a button that I'll press and change the variable value. How can I perform it?

<html>
<body>
<button>
    Button
</button>
<script type="text/javascript">
    var a = 0;
</script>
</body>
</html>

1 Answer 1

3

add an onclick handler to the button :

<html>
<body>
<button onclick="setA()">
    Button
</button>
<script type="text/javascript">
    var a = 0;
    function setA(){
      a=4;
      console.log(a);
    }
</script>
</body>
</html>

Sign up to request clarification or add additional context in comments.

13 Comments

As it, every time but is pressed var a would be re-initialized.
you mean like set to 0 beforehand ? cause I tried with a++ instead and it just keeps increasing oO
Yes jonathan. The correct would be set a=0 in a script other than that linked to button, before this one. So you initialize once and everytime but is pressed then proceed with desired calculation.
not sure what you mean but the script tag is only running once only the setA function is called onclick
Hey, I want to ask a little question, how do I add a text after pressing the button, for example instead of adding it to console chat?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.