为什么最后一个' In Stock'字段替换所有其他'库存'当我试图对数量施加价值时,哪个领域?
<form action="add_sales.php" method="POST">
<table class="table table-striped table-bordered table-hover results table-fixed">
<thead>
<tr>
<th class="text-center">#</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
<th>In Stock</th>
<th style="width: 20%">Quantity</th>
</tr>
<tr class="warning no-result">
<td colspan="8"><i class="fa fa-warning"></i> No Product Found</td>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM products";
$exec = mysqli_query($connection, $query);
$a = 1;
$b = 1;
while ($row = mysqli_fetch_array($exec)) {
$product_id = $row['product_id'];
$product_name = $row['product_name'];
$product_price = $row['sell_price'];
$description = $row['description'];
$product_quantity = $row['quantity'];
}
?>
<tr>
<td class="text-center"><?php echo $product_id; ?><input type="hidden" name="product_id[]" value="<?php echo $product_id; ?>"></td>
<td><?php echo $product_name; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $product_price; ?></td>
<td><input type="number" name="hehe" value="<?php echo $product_quantity; ?>" id="<?php echo "qtyResult" . $a++; ?>" disabled></td>
<td><input type="number" name="qtyBuy[]" id="<?php echo "qtyBuy" . $b++; ?>" onkeyup="updateStock(this, event)"></td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="form-group">
<input type="submit" name="addCart" value="Add Items to Cart" class="btn btn-info pull-right">
</div>
</form>
这是我的jQuery脚本。我认为问题出在var inStock
的价值中。当我将var inStock
的值更改为固定数字时,它的工作正常。
function updateStock(obj, event) {
var inputQty = obj.value;
var inStock = "<?php echo $product_quantity; ?>";
$(obj).closest('tr').find('input[id^="qtyResult"]').val(inStock - inputQty);
}
答案 0 :(得分:0)
因为$product_quantity
将被设置为循环中的最后一个值。
如果您查看源代码并查看javascript函数,您会看到它:
function updateStock(obj, event) {
var inputQty = obj.value;
var inStock = "234"; //or whatever the last value was
$(obj).closest('tr').find('input[id^="qtyResult"]').val(inStock - inputQty);
}
由于页面加载后值可能会发生变化(因此在php退出后),你应该在需要时从dom中获取当前值:
function updateStock(obj, event) {
var inputQty = obj.value;
var quantityInput = $(obj).closest('tr').find('input[id^="qtyResult"]');
quantityInput.val(quantityInput.val() - inputQty);
}