You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过AJAX向PHP页面传递变量时的加减按钮异常问题

Fixing the Quantity Update Issue for Multiple Products

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 & between rowid and qty, which would have made the query string invalid (it would look like rowid=123qty=4 instead of rowid=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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:40:15