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

PHP-Ajax表格onchange无刷新更新问题:仅首个输入框生效

问题原因及解决办法

问题出在HTML的ID属性必须唯一,你的PHP循环生成了多个id="mod"和id="ctgr"的元素,而jQuery的$('#mod')选择器只会匹配DOM中第一个带该ID的元素,所以只有第一个输入框能触发change事件,其余的都没反应。

修复步骤:

1. 修改PHP代码,替换重复ID为类名/数据属性

把重复的ID改成类名,同时给每个输入框绑定对应的ctgr值(推荐用data-*属性,省去额外隐藏域):

while($xx < count($testa))
{
    $testaecho .= "<th>".$testa[$xx]."</th>";
    $corpoecho .= "<td style=' max-width: 20px;'>";
    $corpoecho .= "<form name='changeqta' method='post' action='' class='qta-form'>";
    // 用类名替代ID,通过data-ctgr绑定对应的值
    $corpoecho .= "<input type='number' maxlength='3' class='mod-input' value='".$corpo[$xx]."' data-ctgr='".$idriga[$xx]."'>";
    $corpoecho .= "</form>";
    $corpoecho .= "</td>";
    $xx++;
}

echo "<tr>".$testaecho."</tr>";
echo "<tr>".$corpoecho."</tr>";

2. 调整jQuery代码,绑定类选择器并获取对应数据

用类选择器给所有输入框绑定change事件,通过当前元素的data属性拿到对应的ctgr值:

<script>
$(document).ready(function(){
    $('.mod-input').on('change', function(){
        var name = $(this).val();
        var ctgr = $(this).data('ctgr');
        
        $.ajax({
            url:'update.php',
            method:'POST',
            data:{
                name: name,
                ctgr: ctgr
            },
            success:function(response){
                alert(response);
            }
        });
    });
});
</script>

如果坚持要用隐藏域的方式,PHP里保留隐藏域但改成类名:

$corpoecho .= "<input type='hidden' class='ctgr-input' value='".$idriga[$xx]."'>";

对应的jQuery代码改成:

<script>
$(document).ready(function(){
    $('.mod-input').on('change', function(){
        var name = $(this).val();
        // 找到当前表单下的隐藏域
        var ctgr = $(this).closest('.qta-form').find('.ctgr-input').val();
        
        $.ajax({
            url:'update.php',
            method:'POST',
            data:{
                name: name,
                ctgr: ctgr
            },
            success:function(response){
                alert(response);
            }
        });
    });
});
</script>

内容的提问来源于stack exchange,提问作者Stefano Coccia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:00:31