Issue
I'm trying to make a calculator I wanted to take the number and the operation from the input and onclick to display the result in another input field. Just to test if the button work console.log(num1+num2) but I see no result in the console log. and i also what to know how i can pass my operation from the input
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
var oper = document.getElementById("oper").value;
var cal = document.getElementById("cal").value;
var res = document.getElementById("num1").value;
var calculatorBtn = document.getElementById("calculator");
const form = document.querySelector("formCal");
function calculate() {
console.log(num1 + num2);
}
<div class="root">
<h1>Calculator</h1>
<form action="" id="formCal">
<div class="calculator">
<div class="box">
<label for="num1">Number 1</label>
<input type="number" placeholder="num1" id="num1">
</div>
<div class="box">
<label for="num2">Number 2</label>
<input type="number" placeholder="num2" id="num2">
</div>
<div class="box">
<label for="oper">operation</label>
<input type="text" placeholder="oper" id="oper">
</div>
<div class="box">
<label for="res">Result</label>
<input type="number" placeholder="res" id="res">
</div>
<div class="box">
<input type="button" id="cal" value="calculator" placeholder="calculate" onclick="calculate()" />
</div>
</div>
</form>
</div>
Solution
Once you have a string for the calculation, you can run the eval()
function to execute the calculation as JavaScript code.
Since you are generating a string, you might not need the parseInt
at all.
Using eval()
poses a potential security risk, if you publish a site using it. Use it only for your learning experiments.
function calculate(){
const num1 = document.getElementById("num1").value;
const num2 = document.getElementById("num2").value;
const oper = document.getElementById("oper").value;
document.getElementById('res').value = eval(num1 + oper + num2);
}
Answered By - Andy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.