1 回答

TA貢獻1850條經驗 獲得超11個贊
您可以使用單獨的表單 ID,如下所示...
看法
<?php
$stmt = $conn->prepare("SELECT * FROM product");
if ($stmt->execute()){
$result = $stmt->get_result();
$i = 1; // added
while ($row = $result->fetch_assoc()){
?>
<div class="col-xl-3 col-md-4 mb-4">
<div class="card border-bottom-secondary h-100">
<div class="embed-responsive embed-responsive-16by9">
<img src="img/<?php echo $img_src; ?>" alt="" class="card-img-top embed-responsive-item">
</div>
<div class="card-body">
<form id="saveform<?=$i?>"> <!-- form id added -->
<div>
<h4 class="text-primary"><?php echo $row['name']; ?></h4>
</div>
<div>
<input type="text" id="name" name="name" value="<?php echo $row['name']; ?>" hidden>
<label for="quantity">Qty. </label>
<input class="w-25" onclick="this.select();" min="1" name="quantity" value="1" type="number" id="quantity">
<button type="button" id="save" onclick="saveTemp(this)">Add</button> <!-- pass 'this' from here-->
</div>
</form>
</div>
</div>
</div>
<?php
$i++; //incremented here
}
}
?>
在您的腳本中進行更改...
js
function saveTemp(these) {
var formId = $(these).closest("form").attr("id"); // get form id here
var productName = $('#'+formId+' #name').val(); // assigned form id here
var quantity = $('#'+formId+' #quantity').val(); // assigned form id here
//console.log(productName);
//console.log(quantity);
$.ajax({
type: "POST",
url: "purchase.php",
data: {
product: productName,
quantity: quantity
},
success: function(){
alert('success');
}
});
return false;
}
添加回答
舉報