Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make buttons that increment and decrement a value when clicked?

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>
like image 559
T. Ou Avatar asked Dec 03 '22 12:12

T. Ou


1 Answers

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>
like image 130
Angelos Chalaris Avatar answered Dec 06 '22 12:12

Angelos Chalaris