Odie Odie - 4 months ago 12
Javascript Question

Selecting an appending ID attribute with jQuery

Why does the last 'In Stock' field replaces every other 'In Stock' field when I'm trying to place value on the quantity?

<form action="add_sales.php" method="POST">
<table class="table table-striped table-bordered table-hover results table-fixed">
<th class="text-center">#</th>
<th>Product Name</th>
<th>In Stock</th>
<th style="width: 20%">Quantity</th>
<tr class="warning no-result">
<td colspan="8"><i class="fa fa-warning"></i> No Product Found</td>
$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'];
<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>
<?php } ?>
<div class="form-group">
<input type="submit" name="addCart" value="Add Items to Cart" class="btn btn-info pull-right">

Here is my jQuery script. I think the problem is in the
var inStock
's value. When I change the
var inStock
's value to a fixed number, it's working fine.

function updateStock(obj, event) {
var inputQty = obj.value;
var inStock = "<?php echo $product_quantity; ?>";
$(obj).closest('tr').find('input[id^="qtyResult"]').val(inStock - inputQty);

Relevant Table Image


Because $product_quantity will be set to the last value in the loop.

If you view source and look at the javascript function, you will see it reads:

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);

As the values can change after the page has loaded (and therefor after php has quit) you should grab the current value from the dom when you need it:

function updateStock(obj, event) {
    var inputQty = obj.value;
    var quantityInput = $(obj).closest('tr').find('input[id^="qtyResult"]');
    quantityInput.val(quantityInput.val() - inputQty);