JSFiddle - React, Tailwind, and code Playground
HTML
Num 1:<input type="text" id="num1" name="num1" onblur="change()" /><br />
Num 2:<input type="text" id="num2" name="num2" /><br />
Result :<input type="text" id="ans" name="ans"><br />
<input type="button" id="One" value="1" onclick="getValue('One')">
<input type="button" id="Two" value="2" onclick="getValue('Two')">
<input type="button" id="Three" value="3" onclick="getValue('Three')">
<input type="button" value="+" onclick="add()"><br />
<input type="button" id="Four" value="4" onclick="getValue('Four')">
<input type="button" id="Five" value="5" onclick="getValue('Five')">
<input type="button" id="Six" value="6" onclick="getValue('Six')">
<input type="button" value="-" onclick="sub()"><br />
<input type="button" id="Seven" value="7" onclick="getValue('Seven')">
<input type="button" id="Eight" value="8" onclick="getValue('Eight')">
<input type="button" id="Nine" value="9" onclick="getValue('Nine')">
<input type="button" value="*" onclick="mul()"><br />
<input type="button" id="Zero" value="0" onclick="getValue('Zero')">
<input type="button" value=" Clear " onclick="clr()">
<input type="button" value="/" onclick="div()"><br/>
JavaScript
var text = '';
var id = '';
//initially input is enterd into first textbox i.e it is the current input box
var setId = "num1";
var n1 = '';
var n2 = '';
var res = '';
//onblur from first textbox, sets the second textbox as the current input box
function change() {
setId = "num2";
n1 = text;
}
// to enter into current input textbox value of the button pressed
function getValue(id) {
var n;
n = document.getElementById(id).value; //i think problem is here
text = text + n; //to concatenate in whatever is previously entered in the textbox
document.getElementById(setId).value = text;
}
//to clear both textboxes
function clr() {
document.getElementById("num1").value = "";
document.getElementById("num2").value = "";
text = "";
}
//to display the result inside the result textbox
function display() {
//document.getElementById("ans") = res;
}
function add() {
n2 = document.getElementById("num2").value;
n1 = document.getElementById("num1").value;
res = parseInt(n1) + parseInt(n2);
document.getElementById("ans").value = res;
display();
}
function sub() {
n2 = document.getElementById("num2").value;
n1 = document.getElementById("num1").value;
res = parseInt(n1) - parseInt(n2);
document.getElementById("ans").value = res;
display();
}
function mul() {
n2 = document.getElementById("num2").value;
n1 = document.getElementById("num1").value;
res = parseInt(n1) * parseInt(n2);
document.getElementById("ans").value = res;
display();
}
function div() {
n2 = document.getElementById("num2").value;
n1 = document.getElementById("num1").value;
res = parseInt(n1) / parseInt(n2);
document.getElementById("ans").value = res;
display();
}