Skip to content Skip to sidebar Skip to footer

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 it

Solution 1:

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;
      }
      varnumber = 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.

Solution 2:

You should handle 'onkeyup' and 'onpaste' events to ensure you capture changes by keyboard and via clipboard paste events.

<inputid='myinput' /><script>var myinput = document.getElementById('myinput');
  functionchangeHandler() {
    // here, you can access the input value with 'myinput.value' or 'this.value'
  }
  myinput.onkeyup = myinput.onpaste = changeHandler;
</script>

Similarly, use getElementById and the element's innerHTML attribute to set the contents of an element when you want to show the result.

Post a Comment for "Javascript Calculator As Users Type Numbers"