I’m learning to code in JavaScript and HTML to try and learn some web development and I am trying to figure out how to make a HTML button be able to add a value to a JavaScript variable
My code is not working how I would like. You can probably tell what I’m trying to do but can someone tell me how I’m meant to do it.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var number = 123;
function docWrite(variable) {
document.write(variable);
}
function addOne(variable) {
variable + 1
}
</script>
</head>
<body>
<h1>
<script>
docWrite(number)
</script>
</h1>
<button><script>addOne(number)</script></button>
</body>
</html>
2
Answers
you should use this code
First thing, your button is empty, with no text the button can’t appear.
So you need to add text to your button like this:
Second thing you need to call your addOne function each time your button is pressed with a onclick trigger :
After these two things you need to edit some things in your JS
First select and edit your h1 tag with innerHTML otherwise you will overwrite your full document on first click. With document.selector & innerHTML only your tag will be edit.
In addOne Function i’ve replaced variable +1 with variable++(The same but cleaner), rewrite number so your value is updated for your next itteration then write again on your h1
With these things your code should work. 🙂
I’ve grouped JS also ( cleaner )
Hope it will help
Full code : https://codepen.io/ColinMsd/pen/WNLJdmp?editors=1001
Post Edit: For your button you can also use AddEventListener to call an event on each click like this:
And HTML:
Same result just a bit more complicated process but much cleaner:)