0
<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>
Irevall
  • 1
  • 1
  • 4
  • Where is the code ? – Supradeep Jan 13 '17 at 19:10
  • `ValueChanged`: "Specification: XUL".`input` should be used instead. Please show the code with `input` event, __in the post__, and explain in details what goes wrong. – Teemu Jan 13 '17 at 19:16
  • @suzo its a pastebin link. – Rafique Ahmed Jan 13 '17 at 19:18
  • @Teemu it's pastebin link. Just change 'ValueChange' to 'input'. I've already explained how it goes wrong. It's triggered when writting LETTERS, which input type number doesn't let go through, so, on the screen of the User nothing changes, but the Total is cleaned. – Irevall Jan 13 '17 at 19:28
  • @Teemu http://pastebin.com/QA3se4WA Write any numbers, add them, and now try to write some latters into any bracket. The sum gets wiped out. – Irevall Jan 13 '17 at 19:29
  • @Teemu, done, can I somehow flatten it so it doesn't take up half the space? I'm onto translating it aswell. – Irevall Jan 13 '17 at 19:42
  • No need for flattening, the code is fine as it is. Translating is not oblique, but if you're on it already, it is wellcome. – Teemu Jan 13 '17 at 19:45
  • @Teemu, done. If I won't find any solutions I'll just swap input type to text and go with input event listener. – Irevall Jan 13 '17 at 19:52
  • Note, that despite of type of number, the value of an input is always a string. You could convert the value to a number, then check, if you really got a number, and if yes, then call `cleanup` only. See http://stackoverflow.com/a/1830844/ for number check. Note also, that type of number forces user to use localized decimal delimitter, but a dot is always used in the returned value. – Teemu Jan 13 '17 at 19:59
  • @Teemu ye, but it shouldn't matter that it's a string, since in type=number letters are not registred, so they shouldn't change the Value. Unless they are registred and quickly getting ridden of. But the thing is, ValueChange doesn't work incorrectly, it doesn't work at all. It doesn't do anything. – Irevall Jan 13 '17 at 20:07
  • `input` is still triggered. You could try `change` event instead, that won't fire before you focus somewhere else on the page. Like I 've said in my first comment, `ValueChange` is a XUL event, it is not implemented within DOM events. Also, e.g. FireFox lets you to enter letters too, it just turns the input to red after focusing somewhere else. – Teemu Jan 13 '17 at 20:09

2 Answers2

0

If I understand correctly, I believe what you want is addEventListener('keydown', function()). Like so:

document.getElementById('liczba1').addEventListener('keydown', function(e) {
   if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
      czyszczenie();
});

Explanation:

When using Event Listeners an Event object is passed into the function giving you information about the event that has occurred. In this case the keydown event object has information about which the key has been pressed.

Full Code Example:

function dzialanie(x) {
  var typDzialania = x;
  var n1 = document.getElementById('liczba1').value;
  var n2 = document.getElementById('liczba2').value;
  var wynik = '';
  console.log('Typ dzialania: ' + typDzialania);
  console.log('Liczba 1: ' + n1);
  console.log('Liczba 2: ' + n2);

  if (isNumber(n1) == false || isNumber(n2) == false) {
    alert('Wprowadź poprawne dane');
    return false;
  }
  n1 = Number(n1);
  n2 = Number(n2);

  switch (typDzialania) {
    case '+':
      wynik = (n1 + n2);
      break;
    case '-':
      wynik = (n1 - n2);
      break;
    case '*':
      wynik = (n1 * n2);
      break;
    case '/':
      if (n2 == 0) {
        alert('Nie dziel przez 0!!!');
        czysczenie();
        return false;
      }
      wynik = (n1 / n2);
  }
  document.getElementById('wynik').innerHTML = wynik;
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function czyszczenie() {
  document.getElementById('wynik').innerHTML = '';
}

document.addEventListener('DOMContentLoaded', function() {
  var dodawanie = document.getElementById('dodawanie');
  var odejmowanie = document.getElementById('odejmowanie');
  var mnozenie = document.getElementById('mnozenie');
  var dzielenie = document.getElementById('dzielenie');
  dodawanie.addEventListener('click', function() {
    dzialanie(dodawanie.value);
  });
  odejmowanie.addEventListener('click', function() {
    dzialanie(odejmowanie.value);
  });
  mnozenie.addEventListener('click', function() {
    dzialanie(mnozenie.value);
  });
  dzielenie.addEventListener('click', function() {
    dzialanie(dzielenie.value);
  });
  document.getElementById('liczba1').addEventListener('keydown', function(e) {
    if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
      czyszczenie();
  });
  document.getElementById('liczba2').addEventListener('keydown', function(e) {
    if(e.which >= 48 && e.which <= 57) //if 0-9 is pressed
      czyszczenie();
  });
});
<!DOCTYPE html>
<html>

<body>
  <table>

    <tr>
      <td>Liczba 1</td>
      <td>Liczba 2</td>
    </tr>
    <tr>
      <td>
        <input type='number' id='liczba1' />
      </td>
      <td>
        <input type='number' id='liczba2' />
      </td>
    </tr>
  </table>
  <input type='button' id='dodawanie' value='+' />
  <input type='button' id='odejmowanie' value='-' />
  <input type='button' id='mnozenie' value='*' />
  <input type='button' id='dzielenie' value='/' />
  <div id='tekst'>
    Wynik: <span id='wynik'></span>
  </div>
</body>

</html>
imtheman
  • 4,713
  • 1
  • 30
  • 30
  • You can't rely on `which` here. It's just a keyboard key mapping code, and might vary depending on the keyboard. – Teemu Jan 13 '17 at 20:20
  • @Teemu sorry for using non permanent link again: http://i.imgur.com/WvPNlgm.png Can I just get the value of 'key' and check if it's a number? – Irevall Jan 13 '17 at 20:33
  • @Irevall No, Teemu is incorrect. http://stackoverflow.com/questions/4471582/javascript-keycode-vs-which – imtheman Jan 13 '17 at 20:36
  • It is key mapping. Hit `1` on the number pad, you'll see. `event.key` in modern browsers represents the entered character. – Teemu Jan 13 '17 at 20:43
  • @Teemu Yes, `event.key` would, but not `event.which` or `event.keyCode`. – imtheman Jan 13 '17 at 20:46
  • Sorry, I misread your comment. Yes, `event.key` works on most browsers, but `event.which` or `event.keyCode` work on all of them. Perhaps the best way would be to see if `event.key` exist then use that if it does. Other wise fall back to `event.which` or `event.keyCode`. – imtheman Jan 13 '17 at 20:57
  • @imtheman Please read [the docs](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent) "__KeyboardEvent.which__ _Read only Returns a Number representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode._" + it is deprecated, as well as `keyCode`. – Teemu Jan 13 '17 at 20:59
0

SOLUTION, thanks to discussion between @Teemu and @imtheman, thanks a lot guys!

<!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('keydown', function(e) {
                    if (isNumber(e.key)) {
                        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>

Explanation:

  1. My first bite into it, ValueChange is useless, because it's XUL (dunno what it is yet, but it's useless), gotta use something DOM-related
  2. I have to use one of the event listeners I've tried before (keydown/input), but filter the result
  3. I am bad with using objects, and the keydown event object is much easier to understand than input one (much simplier)
  4. e.key (or event.key) gives me the value of key property of event
  5. So now we need to validate if key pressed is a number or not.
  6. But we can't use inbuilt function of Number(), because empty slots, like Number(' '), equal 0
  7. So I make my own function, isNumber. And voilà.
Irevall
  • 1
  • 1
  • 4