jQuery+Laravel7动态新增行带下拉文本框自动计算总金额问题求助
修复方案
修改说明
- 替换原有直接绑定事件的逻辑为事件委托,保证动态新增的行元素也能触发计算回调
- 调整计算逻辑为按行遍历,通过DOM层级获取当前行的服务单价、重量、附加项数值,避免ID重复导致只能读取第一行数据的问题
- 新增附加项非空判断,未填写附加项的行不计入总金额
完整修改后的@section('scripts')代码
@section('scripts') <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script> <script type="text/javascript"> // CSRF Token var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content'); $(document).ready(function(){ $( "#customer_search" ).autocomplete({ source: function( request, response ) { // Fetch data $.ajax({ url:"{{route('Autocomplte.getAutocomplte')}}", type: 'post', dataType: "json", data: { _token: CSRF_TOKEN, search: request.term }, success: function( data ) { response( data ); } }); }, select: function (event, ui) { console.log(ui.item); $('#customer_search').val(ui.item.value); $('#cust_name').val(ui.item.label); $('#cust_id').val(ui.item.id); return false; } }); // 动态添加服务行 var j = 1; $("#addserv").click(function(){ $(".container").append(`<div class='input-group mb-3'> <select class='form-control col-md-5 mr-2' name=''> @foreach ($services as $s) <option data-index='{{$loop->index}}' value='{{$s->servicePrice}}' >{{$s->serviceName}}</option> @endforeach </select> <input type='number' class='form-control col-md-3 mr-2' name='quantity' placeholder='weight/size' data-index='${j}' > <input type='number' class='form-control col-md-3 mr-2' name='addonqty' placeholder='add-on' data-index='${j}' > <button type='button' class='minus btn btn-danger'><i class='fas fa-minus-circle'></i></button> </div>`); j++; }); // 删除行 $("body").on("click", ".minus", function() { $(this).closest("div").remove(); calculateTotal(); }); // 事件委托绑定计算事件,动态生成元素也可触发 $(document).on('change keyup', 'select, input[type="number"]', calculateTotal); // 总金额计算逻辑 function calculateTotal(){ var total = 0; // 遍历每一行服务 $('.input-group').each(function(){ const servicePrice = parseFloat($(this).find('select option:checked').val()) || 0; const weight = parseFloat($(this).find('input[name="quantity"]').val()) || 0; const addonQty = parseFloat($(this).find('input[name="addonqty"]').val()) || 0; // 重量不为空、附加项不为空时才计算该行金额 if(weight > 0 && addonQty > 0){ total += servicePrice * weight * addonQty; } }); $('#total').val(total.toFixed(2)); } }); </script> @endsection
可选调整说明
如果需求实际为「附加项未填写时默认按1计算,仅重量为空时不计入」,只需将计算逻辑的判断条件修改为:
if(weight > 0){ const opt = addonQty > 0 ? addonQty : 1; total += servicePrice * weight * opt; }
内容的提问来源于stack exchange,提问作者thevioletic1
相关产品推荐
相关产品推荐

