我有一个页面,用户可以在其中提交表格,这很好,但我希望有一个数量字段,用户可以输入数字,在总数框中,当他们更新数量时,它会显示总数。我希望在不重新加载页面的情况下实现这一点。我认为javascript是最好的方法,但我不确定如何做到这一点,因为我对javascript没有任何经验。非常感谢您的帮助!!!
到目前为止我的代码:
<form>
<table align="center">
<tr>
<td colspan="3" align="center"><img src="<?php echo getProductImage($product_id); ?>" title="<?php echo getProductName($product_id); ?>" /></td>
</tr>
<tr>
<td colspan="3"><br/></td>
</tr>
<tr>
<td align="center">Quantity:</td>
<td colspan="2"></td>
</tr>
<tr>
<td><input type="number" min="64" max="9999" name="quantity" /></td>
<td> @ $<?php echo number_format((getProductPrice($product_id)/2),4); ?>/per item = </td>
<td>Total Goes Here</td>
</tr>
</table>
</form>
请参阅此JSFiddle(注意添加的data-product-price
属性)
HTML
<table align="center">
<tr>
<td align="center">Quantity:</td>
<td colspan="2"></td>
</tr>
<tr>
<td><input type="number" min="64" max="9999" name="quantity" /></td>
<td> @ $345.50/per item = </td>
<td data-product-price="345.50"></td>
</tr>
</table>
JavaScript
$(function(){
$("input[name='quantity']").on("input", function(){
var $outputCell = $(this).parent().siblings("[data-product-price]").eq(0);
$outputCell.html((+$outputCell.data("product-price") * +$(this).val()).toFixed(2));
});
});
使用jQuery和Javascript的最小示例可以是:
<form>
Quantity: <input type="text" id="quantityField">
<div>Total: <span id="totalField">0</span> $ (5$/item)</div>
</form>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
// The line above loads jQuery
// Javascript code goes here. You would normally have this in a separate file.
// Somehow fetch the desired price from your program
var pricePerItem = 5;
// This code executes when the quantityField elements value changes
$('#quantityField').on('input',function(event){
// 1. Read quantity
var quantity = $(this).val();
// 2. Calculate total
var total = pricePerItem * quantity;
// 3. Update total field
$('#totalField').text(total);
});
</script>
请注意,这是一个最小的例子,在安全、代码放置等方面没有遵循javascript编程的最佳实践,但它可能只会对您有所帮助。
您可以尝试在禁用的输入中回显每个产品的价格,或者添加一个隐藏的输入,即每个产品的价值。
然后你可以试试这个JS:
$('your_quantity_input').on('change', function() {
var quantity = $(this).val();
var price = $('your_hidden_input').val();
var total = quantity * price;
$('your_td_total').html(total);
});
这是通过使用jQuery实现的。
以下是工作示例:
https://jsfiddle.net/LzLep9ez/