简体   繁体   中英

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. When I use the cursor to change the input value, the output for the 'price' variable is "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? I've got this much so far on my own:

Here is my HTML:

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

And my 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.

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.

$(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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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