Calculator, how can I store a value after click on plus symbol and give the sum after click on equal symbol?

Viewed 364

I'm making a calculator but have a problem storing the value after clicking on the plus symbol and then choose another number to click on the equal symbol and get the result. Help me please! XP

let firstValue;
let secondValue;

document.querySelector('#addOperator').addEventListener('click', function() {
 if(document.querySelector('#addOperator')) {
  firstValue = document.querySelector('#output').textContent;
  // document.querySelector('#output').textContent = '';
  // console.log(firstValue);
  console.log(document.querySelector('#output').textContent);
 };
});

document.getElementById('equals').addEventListener('click', function() {
 if(document.querySelector('#output').textContent === firstValue) {
  secondValue = document.querySelector('#output').textContent;
  // console.log(secondValue);
  // document.querySelector('#output').textContent = add(firstValue, secondValue);
  console.log(document.querySelector('#output').textContent = add(firstValue, secondValue));
 };
});

My html document is this------------------------------------------------------------->

    <!-- Calculator display  -->
<div id="output">
  <!-- <div id="previous-operand"></div>
  <div id="current-operand"></div> -->
</div>

<button class="span-two" id="ac-color">AC</button>
<button id="clear-entry">CE</button>
<button id="divideOperator">÷</button>
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button id="multiplyOperator">*</button>
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button id="addOperator">+</button>
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button id="subtractOperator">-</button>
<button class="number">0</button>
<button class="number">.</button>
<button class="span-two" id="equals">=</button>
1 Answers

this will work i haven't added the add buttons but simply when you click on the operation, set a flag to check when you click calculate to say whether its an add/subtract etc

<input type="button" value="1" onclick="add(event)" />
<input type="button" value="2" onclick="add(event)"/>
<input type="button" value="3" onclick="add(event)"/>
<input type="button" value="4" onclick="add(event)"/>
<input type="button" value="Equals" onclick="calculate()"/>
...
<script>
var nums = [];

var add = function(e){
  nums.push(Number(e.target.value));
}

var calculate = function(){
  var res =0;
  if(nums.length > 0){  
    nums.forEach(function(num){
      res += num;
    });
  }
  alert(res);
  return res;
}
</script>
Related