<input id="num_1" type="number" pattern="[0-9]*" value="1">
<input id="action" type="text" pattern="[-+*/]{1}" value="+">
<input id="num_2" type="number" pattern="[0-9]*" value="2">
<hr>
<input type="text" id="result" disabled />
input:invalid {
border: red solid 3px;
}
const el = {
num_1: document.getElementById('num_1'),
num_2: document.getElementById('num_2'),
action: document.getElementById('action'),
result: document.getElementById('result'),
};
const update = () => {
const val1 = Number(el.num_1.value);
const val2 = Number(el.num_2.value);
const action = el.action.value || '+';
let result = 0;
switch (action) {
case '/':
result = val1 / val2;
break;
case '*':
result = val1 * val2;
break;
case '-':
result = val1 - val2;
break;
case '+':
default:
result = val1 + val2;
}
el.result.value = result;
}
[ el.num_1, el.num_2, el.action ]
.forEach(el => el.addEventListener('input', update));
update();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.