0

how do i create a button that adds a value to another value, i tried like this but every time i run it it makes everything disappear and I only get the operation

      <script>
        var x= 40;
        var y= 40;
         document.write(x);
        </script><br>
        <button onclick="bottone1()" class="butto">+</button>
        <script>
            function bottone1(){
              document.write(x+y)
            }
        </script>
  • As you can read on [MDN documentation for `document.write()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/write), "***Note:** Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document.*". `document.write()` is not the method you need in order to achieve what you want, anyway. – secan Aug 09 '21 at 13:12

2 Answers2

0

Because document.write() rewrites the whole content of the page, so when you run document.write('hi') for example, the only thing that remains in your page would be that hi string. you can also check the jsfiddle

<script>
        var x= 40;
        var y= 40;
         document.write(x);
        </script><br>
        <button onclick="bottone1()" class="butto">+</button>
        <script>
            function bottone1(){
              document.write('hi')
            }
        </script>
Masoud Tahmasebi
  • 423
  • 6
  • 22
0

If u want add value specific element, you can check this.

<html>

<head>
  <title>Write example</title>
<script>
    var x = 40;
    var y = 40;
    
    function newContent() {
        var demo_element = document.getElementById('demo')
        demo_element.innerHTML = x
        x = x + y
    }
  </script>
</head>

<body onload="">
    <button onclick="newContent();">Click Me</button>
    <p id="demo">40</p>
</body>

</html>
Viktor M
  • 301
  • 1
  • 7