Kingsfull123
Kingsfull123

Reputation: 503

Javascript calculator simple clear feature not working

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>

Upvotes: 0

Views: 5682

Answers (2)

Eliott Robson
Eliott Robson

Reputation: 980

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>

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68413

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>

Upvotes: 6

Related Questions