Reputation: 27
So i have a variable lets call that, equation. Which in this case is a string that means "5+10". How do write some code to solve that then put it back into a string to print back to the user?
Upvotes: 1
Views: 52
Reputation: 493
This might help
function Calculate(){
var n1 = document.getElementById("n1").value
var n2 = document.getElementById("n2").value
var op = document.getElementById("op").value
var ans = document.getElementById("ans")
switch(op){
case '+':
ans.value = parseFloat(n1) + parseFloat(n2);
break;
case '-':
ans.value = parseFloat(n1) - parseFloat(n2);
break;
case '*':
ans.value = parseFloat(n1) * parseFloat(n2);
break;
case '/':
ans.value = parseFloat(n1) / parseFloat(n2);
break;
default:
ans.value = "Invalid Operator";
break;
}
}
<p><input type="number" id="n1" style="text-align:center;" placeholder="Enter 1st Number" minimum="0" value="0" oninput="Calculate()" >
<input type="string" max-length="1" id="op" size="5px" style="text-align:center;" placeholder="Operator" oninput="Calculate()">
<input type="number" id="n2" oninput="Calculate()" placeholder="Enter 2nd Number" minimum="0" value="0" style="text-align:center;" ></p>
<input type="disabled" id="ans" placeholder="Answer" style="text-align:center;" >
Upvotes: 1