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

jQuery配合Laravel7实现表单勾选输入后自动计算总价问题排查

问题排查

你现有代码存在以下几处核心错误:

  • 总金额更新逻辑位置错误:你仅在页面初始化时赋值了一次#total的文本,后续复选框、数量输入框触发change事件时没有同步更新总金额展示
  • DOM关联逻辑错误:循环渲染的数量输入框重复使用了id="quantitys",id为页面唯一属性,重复id会导致DOM选择异常,且你原有逻辑没有将复选框和同属一行的数量输入框做绑定
  • 语法错误:$ (this)中间多余空格、$(this).val().attr('quantitys')写法错误(.val()返回的是字符串,无法调用jQuery的attr方法)、attr('quantitys')前缺少jQuery选择对象
  • 事件判断逻辑错误:如果change事件是数量输入框触发的,该元素本身没有:checked状态,原有判断条件会直接失效
  • 总金额累加逻辑错误:total变量未在每次计算前重置,多次触发事件会导致金额重复累加

修复方案

1. 修正Blade模板代码

@foreach ($services as $s)
<tr class="service-row">
    <td>
        <div class="custom-control custom-checkbox">
           <input type="checkbox" name="serviceName" class="custom-control-input service-checkbox" id="customCheck{{$loop->index}}" value="{{$s->servicePrice}}" >
            <label class="custom-control-label" for="customCheck{{$loop->index}}">{{$s->serviceName}} {{$s->servicePrice}}</label>
        </div>
    </td>
    <td>
        <input type="number" class="form-control service-quantity" name="quantity" placeholder="weight/measurements">
    </td>
</tr>
@endforeach
<!-- 总金额展示元素 -->
<div>总金额:<span id="total">0</span></div>

修改点:给每行加service-row类、复选框加service-checkbox类、数量输入框去掉重复id,加service-quantity类,修正了原有多余的引号错误。

2. 修正jQuery代码

// 直接绑定change事件,无需提前遍历元素
$('input.service-checkbox, input.service-quantity').on('change', function() {
    let total = 0;
    // 遍历所有已勾选的复选框
    $('.service-checkbox:checked').each(function() {
        // 匹配当前复选框同属一行的数量输入框
        const $quantityInput = $(this).closest('.service-row').find('.service-quantity');
        const quantity = parseFloat($quantityInput.val()) || 0;
        const price = parseFloat($(this).val()) || 0;
        if (quantity > 0) {
            total += price * quantity;
        }
    });
    // 实时更新总金额,toFixed(2)保留两位小数可按需调整
    $('#total').text(total.toFixed(2));
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:06:04