Home > database >  Javascript Calculator, how do I clear the output when a new number is inputted?
Javascript Calculator, how do I clear the output when a new number is inputted?

Time:09-04

I'm currently building a calculator project and I'm having a small issue. I'm able to get the output of the calculator (e.g., 2 x 2 = 4). However, if I input a new number afterwards, the number gets added to the string of the output. I would like to clear that output ONLY when a new number input is pressed (e.g., 2 x 2 = 4. I press 3, the currentDisplay will show as 43 instead of it just being "3"). Setting

currentNum = "" 

after the output is created does fix this problem, however I wouldn't be able to use the output to chain operators if I did that (e.g., 5 x 2 = 10 2 = 12)

Here is the full code:

let currentNum = "";
let prevNum = "";
let operator = "";
const numberButtons = document.querySelectorAll(".num-btns")
const operatorButtons = document.querySelectorAll(".operator")
const equal = document.querySelector(".equal");
const dot = document.querySelector(".dot");
const clearBtn = document.querySelector(".clear");
const deleteBtn = document.querySelector(".delete");
const currentDisplay = document.querySelector(".current-number");
const prevDisplay = document.querySelector(".previous-number");


//add, subtract, multiply, and divide functions
function addFn(num1, num2) {
    return num1   num2;
}

function subFn(num1, num2) {
    return num1 - num2;
}

function multiFn(num1, num2) {
    return num1 * num2;
}

function divFn(num1, num2) {
    return num1 / num2;
}


//operator function
function operate (a, b, c) {
    const num1 = parseFloat(a);
    const num2 = parseFloat(b);
    let output = 0;
    try {
  
      switch(c) {
        case ' ':
          output = addFn(num1, num2);
          break;
  
        case 'x':
          output = multiFn(num1, num2);
          break;
  
        case '-':
          output = subFn(num1, num2);
          break;
  
       case '/':
          if (num2 === 0) {
            output = "ERROR"
          } else {
          output = divFn(num1, num2);
          }
          break;
      }
    }
    catch(e) {
      currentDisplay.textContent = ("There's an error: ", e)
    };
    currentDisplay.textContent = Math.round(output *100000) / 100000;
    currentNum = output;
}

equal.addEventListener("click", (e) => {
  if (currentNum != "" && prevNum != "") {
  operate(prevNum, currentNum, operator);
  }
  prevNum = "";
});

//button inputs for numbers and operators
numberButtons.forEach(btn => {
    btn.addEventListener("click", (e) => {
        handleNumber(e.target.textContent);
    });
});

function handleNumber(number) {
        currentNum  = number;
        currentDisplay.textContent = currentNum;
}

operatorButtons.forEach((btn) => {
  btn.addEventListener("click", (e) => {
    handleOperator(e.target.textContent);
  });
});

function handleOperator(op) {
  if (currentNum != "") {
    operator = op
    prevNum = currentNum
    prevDisplay.textContent = prevNum   " "   operator;
    currentNum = ""
    currentDisplay.textContent = "";
  }
}

function addDot() {
  if (!currentNum.includes(".")) {
    currentNum  = ".";
    currentDisplay.textContent = currentNum;
  }
}

dot.addEventListener("click", () => {
  addDot();
})

//clear button
function reset() {
  currentDisplay.textContent = "";
  prevDisplay.textContent = "";
  currentNum = "";
  prevNum = "";
}

clearBtn.addEventListener("click", reset);

//delete button
function delNumber() {
  currentDisplay.textContent = currentDisplay.textContent
  .toString()
  .slice(0, -1);
  currentNum = currentDisplay.textContent;
}

deleteBtn.addEventListener("click", delNumber);

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <div >
        <div >
        </div>
        <div ></div>
    </div>
    <div >
        <div>
            <button >AC</button>
            <button >DEL</button>
        </div>
        <div >
            <div >
                <button >7</button>
                <button >8</button>
                <button >9</button>
                <button >/</button>
            </div>
            <div >
                <button >4</button>
                <button >5</button>
                <button >6</button>
                <button >x</button>
            </div>
            <div >
                <button >1</button>
                <button >2</button>
                <button >3</button>
                <button >-</button>
            </div>
            <div >
                <button >.</button>
                <button >0</button>
                <button >=</button>
                <button > </button>
            </div>
        </div>
    </div>
</body>
<script src="./script.js"></script>
</html>

CodePudding user response:

When the = button is clicked, set a variable to remember that the next number input should clear the previous number. (Then remove this catch once an operator button is clicked).

let currentNum = "";
let prevNum = "";
let operator = "";
let clearOnNextNum = false;
const numberButtons = document.querySelectorAll(".num-btns")
const operatorButtons = document.querySelectorAll(".operator")
const equal = document.querySelector(".equal");
const dot = document.querySelector(".dot");
const clearBtn = document.querySelector(".clear");
const deleteBtn = document.querySelector(".delete");
const currentDisplay = document.querySelector(".current-number");
const prevDisplay = document.querySelector(".previous-number");


//add, subtract, multiply, and divide functions
function addFn(num1, num2) {
    return num1   num2;
}

function subFn(num1, num2) {
    return num1 - num2;
}

function multiFn(num1, num2) {
    return num1 * num2;
}

function divFn(num1, num2) {
    return num1 / num2;
}


//operator function
function operate (a, b, c) {
    const num1 = parseFloat(a);
    const num2 = parseFloat(b);
    let output = 0;
    try {
  
      switch(c) {
        case ' ':
          output = addFn(num1, num2);
          break;
  
        case 'x':
          output = multiFn(num1, num2);
          break;
  
        case '-':
          output = subFn(num1, num2);
          break;
  
       case '/':
          if (num2 === 0) {
            output = "ERROR"
          } else {
          output = divFn(num1, num2);
          }
          break;
      }
    }
    catch(e) {
      currentDisplay.textContent = ("There's an error: ", e)
    };
    currentDisplay.textContent = Math.round(output *100000) / 100000;
    currentNum = output;
    clearOnNextNum = true;
}

equal.addEventListener("click", (e) => {
  if (currentNum != "" && prevNum != "") {
  operate(prevNum, currentNum, operator);
  }
  prevNum = "";
});

//button inputs for numbers and operators
numberButtons.forEach(btn => {
    btn.addEventListener("click", (e) => {
        handleNumber(e.target.textContent);
    });
});

function handleNumber(number) {
        if (clearOnNextNum) {
            clearOnNextNum = false;
            currentNum = "";
        }
        currentNum  = number;
        currentDisplay.textContent = currentNum;
}

operatorButtons.forEach((btn) => {
  btn.addEventListener("click", (e) => {
    handleOperator(e.target.textContent);
  });
});

function handleOperator(op) {
  clearOnNextNum = false;
  if (currentNum != "") {
    operator = op
    prevNum = currentNum
    prevDisplay.textContent = prevNum   " "   operator;
    currentNum = ""
    currentDisplay.textContent = "";
  }
}

function addDot() {
  clearOnNextNum = false;
  if (!currentNum.includes(".")) {
    currentNum  = ".";
    currentDisplay.textContent = currentNum;
  }
}

dot.addEventListener("click", () => {
  addDot();
})

//clear button
function reset() {
  currentDisplay.textContent = "";
  prevDisplay.textContent = "";
  currentNum = "";
  prevNum = "";
}

clearBtn.addEventListener("click", reset);

//delete button
function delNumber() {
  currentDisplay.textContent = currentDisplay.textContent
  .toString()
  .slice(0, -1);
  currentNum = currentDisplay.textContent;
}

deleteBtn.addEventListener("click", delNumber);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <div >
        <div >
        </div>
        <div ></div>
    </div>
    <div >
        <div>
            <button >AC</button>
            <button >DEL</button>
        </div>
        <div >
            <div >
                <button >7</button>
                <button >8</button>
                <button >9</button>
                <button >/</button>
            </div>
            <div >
                <button >4</button>
                <button >5</button>
                <button >6</button>
                <button >x</button>
            </div>
            <div >
                <button >1</button>
                <button >2</button>
                <button >3</button>
                <button >-</button>
            </div>
            <div >
                <button >.</button>
                <button >0</button>
                <button >=</button>
                <button > </button>
            </div>
        </div>
    </div>
</body>
<script src="./script.js"></script>

  • Related