Good day. I am practising my javascript skills by making a small calculator. The problem I have encountered is that basically the variable called sum which contains the user input and is displayed on the page isn't displaying properly. It starts from zero.
When I add 2 I get 02 as an output. When I add 2 again insted of 4 I get 022. I am posting the entire source code below.
<!DOCTYPE HTML>
<head>
<title>Screw arround!</title>
<style>
.btn{
width : 50px;
height:50px;
}
.btn2{
width : 200px;
height:50px;
}
.btn3{
width : 200px;
height:25px;
}
</style>
</head>
<body>
<center>
<p id="asd"></p>
<input type="number" id="textField" class="btn3"></input></br>
<button id="add" onclick="compute(this.id)" class="btn">+</button><button id="subtract" onclick="compute(this.id)" class="btn">-</button>
<button id="multiply" onclick="compute(this.id)" class="btn">*</button><button id="divide" onclick="compute(this.id)" class="btn">/</button></br>
<button id="clear" onclick="compute(this.id)" class="btn2">Clear</button>
</center>
</body>
<script>
//----- variables
var sum = 0; // sum
var refr = document.getElementById("textField"); // get a referance to the textField
function compute(id)
{
if(id === "add")
{
sum += refr.value;;
console.log(sum);
}
else if(id === "subtract")
{
sum -= refr.value;
console.log(sum);
}
else if(id === "multiply")
{
sum *= refr.value;
console.log(sum);
}
else if(id === "divide")
{
sum /= refr.value;
console.log(sum);
}
//// set paragraph to the answer
document.getElementById("asd").innerHTML = sum;
if(id === "clear")
{
// make the values zero so new calculations can begin
sum = 0;
refr.value = '0';
document.getElementById("asd").innerHTML = "";
}
}
</script>