Home > database >  Hiding the 0 that shows when a user presses the AC button on my calculator
Hiding the 0 that shows when a user presses the AC button on my calculator

Time:04-19

I've added an AC button to my JS calculator which resets the variables and displays 0 in the displayArea.

However when the user starts typing their first number the 0 stay's so it shows 03 instead of 3 etc - this doesn't impact the calculation.

I've tried to remove this using parseInt and an IF statement however it doesn't seem to work.

My best attempt so far is:

<p id="result-display">    </p>
let displayArea = document.getElementById('result-display');

else if (displayArea.innerHTML = 0) {
        buttonNumber = Number(e.target.innerText);
        displayValue = buttonNumber;
        displayArea.innerHTML = parseInt(displayArea.innerHTML  = displayValue);
        }

If I change the 0 to a string e.g. '0' it works but then also stops the user entering multiple number values e.g. 56 would show as 5 etc.

My JSFiddle is: https://jsfiddle.net/mh85skxv/3/

CodePudding user response:

Add the following line at the end of your calculate function:

displayArea.innerHTML = Number(displayArea.innerHTML);

This will convert the content of the displayArea to a number, eliminating any leading zero.

If you don't want the 0 to appear when pressing AC just replace this line:

displayArea.innerHTML = 0; 

with this:

displayArea.innerHTML = '';

Then parse your number like this in order to avoid NaN:

Number(displayArea.innerHTML) || 0; 

CodePudding user response:

Not sure of the exact solution, but here's a few tips from your question and your Fiddle code:

  • else if (displayArea.innerHTML = 0) { can't work because you need == or ===. Using only the equal sign doesn't check the value of displayArea.innerHTML but assigns it to 0.

  • Also innerHTML is not usually equal to 0...maybe try innerHTML.length or something ?

  • On your fiddle code I notice that you use statements like return firstNumber = .... This is incorrect; instead, declare your variable firstNumber at the top, and for each switch case write something like:

        firstNumber = //whatever you want
        break; //this will ensure your code stops there
    

Hope this helps,

  • Related