Javascript calculator as users type numbers - Stack Overflow

I'm a noob at Javascript, but I'm trying to implement something on my website where users can

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!

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!

Share Improve this question asked Sep 21, 2010 at 4:40 RobHardgoodRobHardgood 5501 gold badge8 silver badges17 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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.

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

<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>

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745436442a4627629.html

相关推荐

  • Javascript calculator as users type numbers - Stack Overflow

    I'm a noob at Javascript, but I'm trying to implement something on my website where users can

    9小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信