简体   繁体   English

如何处理jQuery中数字输入的更改?

[英]How do I handle number input changes in jQuery?

I'm trying to create a checkout menu with jQuery and HTML and I am having trouble getting the input box for the item quantity to behave predictably. 我正在尝试使用jQuery和HTML创建一个结帐菜单,但我无法获得输入框,以使项目数量可预测。 When I use the cursor to change the input value, the output for the 'price' variable is "NaN". 当我使用光标更改输入值时,“ price”变量的输出为“ NaN”。 When I use the arrow keys, the price updates once, but fails after the first change. 当我使用箭头键时,价格更新一次,但是在第一次更改后失败。 How do I get the number input value, multiply it by the text (the price) in the <p> tag, and update the text every time the number is increased or decreased? 如何获取数字输入值,将其乘以<p>标记中的文本(价格),以及每次数字增加或减少时更新文本? I've got this much so far on my own: 到目前为止,我已经拥有了这么多:

Here is my HTML: 这是我的HTML:

<input id="quantity" size="30" type="number" value="1" />
<p id="total">29.99</p>

And my JS: 而我的JS:

$(document).ready(function() {
  function updatePrice() {
  var num = parseInt($("#quantity").val());
  var price = (num) * parseFloat($("#total").text());
  var total = price.toFixed(2);
  $("#total").replaceWith(total);
}
$(document).on("change, keyup, input", "#quantity", updatePrice);
});

JS Fiddle. JS小提琴。

There are only a few changes required to make your code work. 仅需进行少量更改即可使您的代码正常工作。 Be aware that you still need to handle negative numbers (by field properties?) as well as 0. 请注意,您仍然需要处理负数(通过字段属性?)以及0。

$(document).ready(function() {
    // grep the price only once...
    var price = parseFloat($("#total").text());        
    function updatePrice() {        
        var sum, num = parseInt($(this).val(),10);
        // if we have a number
        if(num) {
          // update info text
          sum = num * price;
          $("#total").text(sum.toFixed(2));
        }
    }
    $(document).on("change, mouseup, keyup", "#quantity", updatePrice);
});

Fiddle is here . 小提琴在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM