Laravel 9循环表单实现onchange自动提交及计算问题
Laravel 9 多表单自动提交问题解决
问题情况
循环生成的购物车表单中,修改Qty字段能自动计算Total Price(Qty*Price),但只有第一个表单能自动提交更新数据库,其余表单无响应。尝试为表单ID添加{{$loop->index}}未解决,手动提交按钮(注释部分)可正常工作。
问题根源
- 表单ID重复:原代码所有表单ID都是
editQty,没有实际添加唯一标识,导致document.getElementById('editQty')永远只获取第一个表单。 - 函数重复定义:
hitungTotal函数在循环内部重复渲染,每次循环都会覆盖之前的函数定义,且逻辑里硬编码了固定表单ID。 - 提交逻辑绑定错误:函数里固定查找
editQty表单,没有关联当前输入框所属的表单。
修复后的代码
@foreach($userCarts as $userCart) <div> <h5 class="mt-5">Product Name : {{ $userCart->prodName }}</h5> <!-- 表单ID改为唯一值,用prodID比索引更可靠 --> <form id="editQty-{{$userCart->prodID}}" action="/userCart/{{$userCart->prodID}}/editQty" method="post"> @method('put') @csrf <!--QTY --> <div class="mb-3" style="width: 350px;"> <label for="qty-{{$userCart->prodID}}" class="form-label">Qty</label> <!-- 传递this参数,方便函数定位当前输入框所属表单 --> <input type="number" name="qty" class="form-control" value="{{$userCart->qty}}" id="qty-{{$userCart->prodID}}" onchange="hitungTotal({{$userCart->prodPrice}}, this, 'totalPrice-{{$userCart->prodID}}')" min="1" max="999"> </div> <!-- Harga --> <div class="mb-3" style="width: 350px;"> <label for="price-{{$userCart->prodID}}" class="form-label">Price</label> <input type="number" name="price" class="form-control" value="{{$userCart->prodPrice}}" id="price-{{$userCart->prodID}}" readonly> </div> <!-- Total Price --> <div class="mb-3" style="width: 350px;"> <label for="totalPrice-{{$userCart->prodID}}" class="form-label">Total Price</label> <input type="number" name="totalPrice" class="form-control" value="{{$userCart->qty * $userCart->prodPrice}}" id="totalPrice-{{$userCart->prodID}}"> </div> <!-- <button type="submit"> <p>Save Quantity</p> </button> --> </form> <!-- Untuk delete from cart --> <form action="/userCart/{{$userCart->prodID}}/delete" method="post"> @method('delete') @csrf <button type="submit"> <i class="bi bi-trash3"></i> </button> </form> </div> @endforeach <!-- 将函数移到循环外,避免重复定义覆盖 --> <script> function hitungTotal(harga, inputElement, totalPriceId){ var quantity = inputElement.value; document.getElementById(totalPriceId).value = harga * quantity; // 通过当前输入框找到所属表单并提交,无需依赖固定ID inputElement.closest('form').submit(); console.log(harga); } </script>
关键修改点
- 给表单、输入框添加基于
prodID的唯一ID,解决重复冲突问题 - 将
hitungTotal函数移到循环外部,防止重复定义导致的逻辑覆盖 - 修改
onchange事件传递this参数,让函数直接获取当前输入框元素 - 提交逻辑改为通过
closest('form')定位所属表单,不再依赖固定ID,适配所有循环生成的表单
内容的提问来源于stack exchange,提问作者Julianto Cristian
相关产品推荐
相关产品推荐

