Search code examples
javascriptcalculatoronkeypress

Javascript calculator as users type numbers


I'm a noob at Javascript, but I'm trying to implement something on my website where users can type a quantity, and the subtotal updates dynamically as they type. For example: if items are 10 dollars each, and a user types 5 in the text field I would like it to show $50 next to the text box. Pretty simple multiplication, but I don't know how to do it with Javascript. I think onKeyPress somehow? Thanks!


Solution

  • Assuming the following HTML:

    <input type="text" id="numberField"/>
    <span id="result"></span>
    

    JavaScript:

    window.onload = function() {
       var base = 10;
       var numberField = document.getElementById('numberField');
       numberField.onkeyup = numberField.onpaste = function() {
          if(this.value.length == 0) {
             document.getElementById('result').innerHTML = '';
             return;
          }
          var number = parseInt(this.value);
          if(isNaN(number)) return;
          document.getElementById('result').innerHTML = number * base;
       };
       numberField.onkeyup(); //could just as easily have been onpaste();
    };
    

    Here's a working example.