Reputation: 37
I want to input numbers using buttons into the textbox how to do that?
I have a problem on displaying buttons to textbox, I can only store one function in one button for example <button onclick="getNumber(1)">1</button
>
function calc() {
var a, b, c;
a = Number(document.getElementById('num1').value);
b = Number(document.getElementById('num2').value);
c = document.getElementById('operators').value;
if (c === '+') {
x = document.getElementById('ans').value = (a + b);
}
if (c === '-') {
x = document.getElementById('ans').value = (a - b);
}
if (c === '*') {
x = document.getElementById('ans').value = (a * b);
}
if (c === '/') {
x = document.getElementById('ans').value = (a / b);
}
}
<input type="text" id="num1"><br>
<input type="text" id="num2"><br>
<select id="operators">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<br>
<button onclick="calc()">=</button><br>
<input type="text" id="ans">
Upvotes: 2
Views: 1594
Reputation: 177691
function calc() {
var a, b, c, x = "";
a = Number(document.getElementById('num1').value);
b = Number(document.getElementById('num2').value);
c = document.getElementById('operators').value;
if (c === '+') {
x = (a + b);
} else if (c === '-') {
x = (a - b);
} else if (c === '*') {
x = (a * b);
} else if (c === '/') {
x = (a / b);
}
document.getElementById('ans').value = x;
}
window.addEventListener("load", function() { // when the page loads
document.getElementById("calc").addEventListener("click", calc);
document.getElementById("buts").addEventListener("click", function(e) {
var tgt = e.target;
if (tgt.classList.contains("but")) {
var val = tgt.value;
console.log(val); // not sure what you want to do here
}
});
});
<input type="text" id="num1"><br>
<input type="text" id="num2"><br>
<select id="operators">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<br>
<div id="buts">
<button type="button" class="but" value="1">1</button>
<button type="button" class="but" value="2">2</button>
<button type="button" class="but" value="3">3</button>
</div>
<button type="button" id="calc">=</button><br>
<input type="text" id="ans">
Upvotes: 3