I’m trying to figure out how to get my calculator to perform an operation after hitting equal button. For example, 1+2=4 after pressing ‘equal’ to get 4, I want to press ‘+’ and add the result to a number. At this time it would display the ‘+’ sign instead of doing the operation. Also, I would like to allow user to press the key ‘+’ and it displays only once. At the moment, keys like ‘.’, ‘+’ etc…can be displayed multiple times. I’m new at coding. Any help is appreciated. Here’s the link to my code pen. https://codepen.io/QuidProQuo/full/VMbPgj
JS codes below
var show = document.getElementById('display');
var reset = false;
function clear(){
if(reset){
show.value = '';
reset = false;
}
}
function toScreen(x){
clear();
show.value += x;
if (x === 'c'){
show.value = '';
}
}
function answer(){
x = show.value;
x = eval(x);
show.value = x;
reset=true;
}
function power(){
x = show.value;
x = eval(x*x);
show.value = x;
}
function backspace(){
var num = show.value;
var len = num.length-1;
var newNum = num.substring(0,len);
show.value = newNum;
}
function percent(){
x = show.value;
x = eval(x/100);
show.value = x;
}
function opposite(){
var n = show.value;
n = n * -1;
show.value = n;
}
function sqrt(){
var number = show.value;
var ans = Math.sqrt(number);
if (number < 0) ans="Try Again...";
show.value = ans;
}
function pie(){
var pi = show.value;
var result = Math.PI;
show.value = result;
}
html codes
<h1>Javascript Calculator</h1>
<div id = 'calculator'>
<!--create a form-->
<form>
<input type='text' id='display' disabled>
<br>
<input type='button' value='C' id='keys' onclick='toScreen("c")'>
<input type='button' value='CE' id='keys' onclick='backspace()'>
<input type='button' value='x^2' id='keys' onclick='power()'>
<input type='button' value='+' id='keys' onclick='toScreen("+")'>
<br>
<input type='button' value='9' id='keys' onclick='toScreen("9")'>
<input type='button' value='8' id='keys' onclick='toScreen("8")'>
<input type='button' value='7' id='keys' onclick='toScreen("7")'>
<input type='button' value='-' id='keys' onclick='toScreen("-")'>
<br>
<input type='button' value='6' id='keys' onclick='toScreen("6")'>
<input type='button' value='5' id='keys' onclick='toScreen("5")'>
<input type='button' value='4' id='keys' onclick='toScreen("4")'>
<input type='button' value='*' id='keys' onclick='toScreen("*")'>
<br>
<input type='button' value='3' id='keys' onclick='toScreen("3")'>
<input type='button' value='2' id='keys' onclick='toScreen("2")'>
<input type='button' value='1' id='keys' onclick='toScreen("1")'>
<input type='button' value='/' id='keys' onclick='toScreen("/")'>
<br>
<input type='button' value='0' id='keys' onclick='toScreen("0")'>
<input type='button' value='.' id='keys' onclick='toScreen(".")'>
<input type='button' value='=' id='equal' onclick='answer()'>
<br>