I am new to programming. Every time I run this code, nothing happens. Can you please tell me why this is?
<body>
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<script type="text/javascript">
var x = 0
document.write(x)
function button1() {
document.write(x++)
}
function button2(){
document.write(x--)
}
</script>
</body>
The problem is that you put ++
and --
after the variable, meaning that it will increment/decrement the variable after printing it. Try putting it before the variable, like below.
Also, as mentioned, you have some trouble with document.write()
. Consider the following documentation from the W3Schools page:
The
write()
method writes HTML expressions or JavaScript code to a document.The
write()
method is mostly used for testing. If it is used after an HTML document is fully loaded, it will delete all existing HTML.
Thus, document.write()
will remove all your existing content as soon as you click on a button. If you want to write to the document, use an element's .innerHTML
like this:
var x = 0;
document.getElementById('output-area').innerHTML = x;
function button1() {
document.getElementById('output-area').innerHTML = ++x;
}
function button2() {
document.getElementById('output-area').innerHTML = --x;
}
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<span id="output-area"></span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With