<input type='number' id='number1'/>
This is where I input numbers to later do operations on them (adding up etc). I've got that part covered up, but I wanted to extend this into deleting the total, which is stored in <span id='total'></span>
, anytime something new is written in <input/>
.
Firstly, I tried addEventListener('input', function());
, but the thing is, it works even on input that's not registered. So, since I have <input type='number'/>
if I write in 'abcd' etc. nothing changes, but the total is cleaned, because it triggers 'input' event listener
. So I did some digging, and found ValueChange event listener, but I can't get it to work (but the value of input
obviously changes).
Just to be honest, I checked for solutions, and are responses are either in regards to jQuery or some workarounds.
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title>Kalkulator-JS</title>
<script>
function operation(x) {
var typeOfOp = x;
var n1 = document.getElementById('number1').value;
var n2 = document.getElementById('number2').value;
var total = '';
console.log('Type of operation: ' + typeOfOp);
console.log('Number 1: ' + n1);
console.log('Number 2: ' + n2);
if (isNumber(n1)==false || isNumber(n2)==false) {
alert('Input right data');
return false;
}
n1 = Number(n1);
n2 = Number(n2);
switch (typeOfOp) {
case '+':
total = (n1 + n2);
break;
case '-':
total = (n1 - n2);
break;
case '*':
total = (n1 * n2);
break;
case '/':
if (n2 == 0) {
alert("You can't divide by 0!!!");
czysczenie();
return false;
}
total = (n1 / n2);
}
document.getElementById('total').innerHTML = total;
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function cleanup() {
document.getElementById('total').innerHTML = '';
}
document.addEventListener('DOMContentLoaded', function() {
var sum = document.getElementById('sum');
var subtract = document.getElementById('subtract');
var multiply = document.getElementById('multiply');
var divide = document.getElementById('divide');
sum.addEventListener('click', function() {
operation(sum.value);
});
subtract.addEventListener('click', function() {
operation(subtract.value);
});
multiply.addEventListener('click', function() {
operation(multiply.value);
});
divide.addEventListener('click', function() {
operation(divide.value);
});
document.getElementById('number1').addEventListener('input', function() {
cleanup();
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Number 1</td>
<td>Number2</td>
</tr>
<tr>
<td><input type='number' id='number1'/></td>
<td><input type='number' id='number2'/></td>
</tr>
</table>
<input type='button' id='sum' value='+'/>
<input type='button' id='subtract' value='-'/>
<input type='button' id='multiply' value='*'/>
<input type='button' id='divide' value='/'/>
<div id='text'>
Total: <span id='total'></span>
</div>
</body>
</html>