通过AJAX向PHP页面传递变量时的加减按钮异常问题
Hey there, I see exactly what's going on here—your plus/minus buttons are only working for the first product because of how you're grabbing the quantity value. Let's break this down and fix it quickly!
The Problem
When you click a plus or minus button, this line:
var qty = $('.number').val();
uses a global class selector that grabs the value of the first element with the number class on the page—no matter which button you click. That's why all other products end up using the first item's quantity.
The Fix
Instead of grabbing the first .number input everywhere, you need to target the specific input paired with the clicked button. Since your buttons and quantity input are sibling elements (right next to each other in the HTML), you can use jQuery's siblings() method to find the correct input relative to the clicked button.
Here's the corrected AJAX code:
// WHEN - IS CLICKED $(document).on('click', '.number-minus', function(){ var $button = $(this); var rowid = $button.data("id"); // Get quantity from the sibling input with class "number" var qty = $button.siblings('.number').val(); // Fixed URL parameter separator (added & between rowid and qty) $.ajax({ url:"update.php?rowid="+rowid+"&qty="+qty, method:"POST", data:{rowid:rowid , qty:qty}, dataType:"text", success:function(data){ alert(data); } }); }); // WHEN + IS CLICKED $(document).on('click', '.number-plus', function(){ var $button = $(this); var rowid = $button.data("id"); var qty = $button.siblings('.number').val(); $.ajax({ url:"update.php?rowid="+rowid+"&qty="+qty, method:"POST", data:{rowid:rowid , qty:qty}, dataType:"text", success:function(data){ alert(data); } }); });
Extra Notes
- I fixed a small bug in your URL: you were missing an
&betweenrowidandqty, which would have made the query string invalid (it would look likerowid=123qty=4instead ofrowid=123&qty=4). - Since you're already sending data via POST, you could remove the query string parameters from the URL entirely—they're redundant here, and the POST data will still be processed correctly.
- For even more robustness, wrap each product's controls (minus button, input, plus button) in a container div, then use
$button.closest('.product-container').find('.number').val()—this works reliably even if your DOM structure changes later.
内容的提问来源于stack exchange,提问作者George Albert

