I’m new to javascript. I did a simple calculator that has 2 inputs values with 4 buttons of operators. How can I fix this javascript so that it can count the numbers based on different operators and display the correct output? How to write it using if else condition or switch cases?
Now I have pressed every button it only shows the output with sum only.
function count() {
var n1 = parseFloat(document.getElementById("num1").value);
var n2 = parseFloat(document.getElementById("num2").value);
var optr = document.getElementById("operator").value;
let result;
if (optr == '+') {
result = n1 + n2;
} else if (optr == '-') {
result = n1 - n2;
} else if (optr == '*') {
result = n1 * n2;
} else {
result = n1 / n2;
}
document.getElementById("output").innerHTML = "Total is: " + result;
}
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>
<input type="button" value="+" onclick="count()" id="operator">
<input type="button" value="-" onclick="count()" id="operator">
<input type="button" value="*" onclick="count()" id="operator">
<input type="button" value="/" onclick="count()" id="operator">
<p id="output"></p>
>Solution :
There are many ways to achieve what you want. Here is one that I have prepared by modifying/simplifying your original code:
const in1 = document.getElementById("num1"),
in2 = document.getElementById("num2");
document.addEventListener("click", function(ev) {
if (ev.target.classList.contains("operator")) {
let optr = ev.target.value, n1=+in1.value, n2=+in2.value;
if (optr == '+') result = n1 + n2;
else if (optr == '-') result = n1 - n2;
else if (optr == '*') result = n1 * n2;
else result = n1 / n2;
document.getElementById("output").innerHTML = "Total is: " + result;
}
})
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>
<input type="button" value="+" class="operator">
<input type="button" value="-" class="operator">
<input type="button" value="*" class="operator">
<input type="button" value="/" class="operator">
<p id="output"></p>
A few remarks:
idattributes must always be unique on a page. I replaced theids in your buttons byclassattributes.- the values of your
inputelements must be evaluated at the time the operator button is clicked. - the conversion from text to numerical values is done implicitly by applying the unary
+operator in front ofin1.valueandin2.value. - instead of assigning the handler function through the html-
onclickattribute I used a delegated event attachment: the click event is attached to the whole document but will only cause an action if the actual clicked element (ev.target) has the word "operator" in its class list.