Javascript calculator for users

I am noob in Javascript, but I'm trying to implement something on my website where users can enter a quantity, and the subtotal is updated dynamically as they are entered. For example: if the items have $ 10 each, and the user enters 5 in the text box, I would like it to show $ 50 next to the text box. Pretty simple multiplication, but I don't know how to do this with Javascript. I think KeyPress is somehow? Thank!

+3
source share
2 answers

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 is a working example .

+5
source

onkeyup onpaste, .

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

, getElementById innerHTML , .

0

Source: https://habr.com/ru/post/1765753/


All Articles