0

I am trying to build a simple calculator with Javascript and Im having issues when clearing display content.

Can someone please have a look at my code and let me know why it is not working.

Why won't setting the display value to an empty string work. What am I doing wrong? Tank you guys.

function testing(button){
  var x = button.value;
  document.getElementById("display").innerHTML+=x;
}

function clear() {
  document.getElementById("display").innerHTML = "";
 }
<body>
    <input type="button" id="one" value="1" onClick="testing(this)">
    <input type="button" id="one" value="2" onClick="testing(this)">
    <input type="button" id="one" value="3" onClick="testing(this)">
    <input type="button" id="clear" value="clear" onClick="clear()">

    <h1 id="display"></h1>
  </body>
Ole Haugset
  • 3,651
  • 3
  • 22
  • 43
Kingsfull123
  • 367
  • 4
  • 12

2 Answers2

6

Your method name is conflicting with the id value, just change it to clear1 and it should work.

       function testing(button){
        var x = button.value;
        document.getElementById("display").innerHTML+=x;
        }

       function clear1(){
        document.getElementById("display").innerHTML = "";
       }
<body>
    <input type="button" id="one" value="1" onClick="testing(this)">
    <input type="button" id="one" value="2" onClick="testing(this)">
    <input type="button" id="one" value="3" onClick="testing(this)">
    <input type="button" id="clear" value="clear" onClick="clear1()">

    <h1 id="display"></h1>
    </body>
gurvinder372
  • 64,240
  • 8
  • 67
  • 88
1

The problem is that there is a document.clear function which is taking precedence over your original call. You can test this by typing document.clear into the console.

Try renaming your function to clearDisplay.

function testing(button){
    var x = button.value;
    document.getElementById("display").innerHTML+=x;
}

function clearDisplay(){
    document.getElementById("display").innerHTML = "";
}
<body>
    <input type="button" id="one" value="1" onClick="testing(this)">
    <input type="button" id="one" value="2" onClick="testing(this)">
    <input type="button" id="one" value="3" onClick="testing(this)">
    <input type="button" id="clearDisplay" value="clear" onClick="clearDisplay()">

    <h1 id="display"></h1>
</body>
Eliott Robson
  • 950
  • 9
  • 19