javascript 从jQuery中的数量输入框计算价格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12728092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate price from quantity input box in jQuery
提问by Hyman Johnson
I'm having a small issue calculating price from Quantity in jQuery. Those are the input boxes i have.
我在 jQuery 中从 Quantity 计算价格时遇到了一个小问题。这些是我的输入框。
Quantity: <input type="text" style="width: 50px;" name="quantity" id="quantity" class="txt" value="1" />
Price: <input type="text" style="width: 50px;" name="item_price" id="item_price" class="txt" value="2990" />
Total Price: <input type="text" style="width: 50px;" name="total_price" id="total_price" class="txt" value="" />
回答by Darren
I am assuming you want the formulae or how to get the values of the input elements:
我假设您想要公式或如何获取输入元素的值:
var quantity = $("#quantity").val();
var iPrice = $("#item_price").val();
var total = quantity * iPrice;
$("#total_price").val(total); // sets the total price input to the quantity * price
alert(total);
Edit for Keyup:
为 Keyup 编辑:
$('#quantity').keyup(function() {
var quantity = $("#quantity").val();
var iPrice = $("#item_price").val();
var total = quantity * iPrice;
$("#total_price").val(total); // sets the total price input to the quantity * price
});
回答by SpYk3HH
updatedto show full example in script tags
更新以在脚本标签中显示完整示例
If you want the formula and how you can "see" the change:
如果您想要公式以及如何“看到”更改:
<script type="text/javascript">
$(function() { // In jQuery 1.6+ this is same as $(document).ready(function(){})
$('#quantity, #item_price') // jQuery CSS selector grabs elements with the ID's "quantity" & "item_price"
.on('change', function(e) { // jQuery 1.6+ replcement for .live (dynamically asigns event, see jQuery API)
// in this case, our event is "change" which works on inputs and selects to let us know when a value is changed
// below i use inline if statements to assure the values i get are "Real"
var quan = $("#quantity").val() != "" ? parseFloat($("#quantity").val()) : 1, // Get quantity value
pric = $("#item_price").val() != "" ? parseFloat($("#item_price").val()) : 0; // Get price value
$('#total_price').val(pric*quan); // show total
});
});
</script>