Laravel中如何基于数据库数据实现勾选checkbox生成价格div模块
勾选位置动态生成价格录入区块实现方案
基础背景
项目有3张支持用户编辑的数据表,分别为cars、locations、price,需要在addCars.blade.php视图中实现按勾选位置生成对应价格配置区的功能,关联规则为:Car模型与Price模型为hasMany关联,单台车辆可对应多个不同位置的价格数据。
现有代码问题
你提交的循环代码存在以下可优化/错误点:
- 循环变量命名冲突:
@foreach ($locations as $locations)上下变量名重复,会导致遍历失败 - 所有DOM ID重复:区块ID、输入框ID均为固定值,不符合唯一ID要求,也会导致label点击关联失效
- 表单标签、提交按钮写在循环内部,会重复生成多个按钮和闭合标签,页面结构混乱
完整实现代码
第一步:Blade视图静态结构
<!-- 位置复选框列表 --> <div class="location-check-list"> @foreach ($locations as $location) <div class="form-check"> <input class="form-check-input location-checkbox" type="checkbox" value="{{ $location->id }}" id="location-{{ $location->id }}"> <label class="form-check-label" for="location-{{ $location->id }}"> {{ $location->name }} </label> </div> @endforeach </div> <!-- 价格区块容器 --> <div id="price-container" class="mt-4"></div> <!-- 全局提交按钮 放在循环外面 --> <button type="submit" onclick="location.href='/cars'" class="btn btn-primary mt-3">提交</button>
第二步:JS动态生成价格区块代码
// 监听位置复选框变更 document.querySelectorAll('.location-checkbox').forEach(checkbox => { checkbox.addEventListener('change', function() { const locationId = this.value const locationName = this.nextElementSibling.textContent.trim() const priceBlockId = `price-block-${locationId}` if (this.checked) { // 勾选时生成对应价格区块 const blockHtml = ` <div class="container-fluid fade-in mb-3" id="${priceBlockId}"> <div class="card"> <div class="card-header">${locationName} 定价配置</div> <div class="card-body"> <div class="form-group"> <label for="carnumber-${locationId}">车辆编号</label> <input type="text" class="form-control" name="prices[${locationId}][carnumber]" id="carnumber-${locationId}" placeholder="车辆编号"> </div> <div class="form-group"> <label for="price-${locationId}">基础价格</label> <input type="text" class="form-control" name="prices[${locationId}][price]" id="price-${locationId}" placeholder="基础价格"> </div> <div class="form-group"> <label for="minday-${locationId}">最少租赁天数</label> <input type="text" class="form-control" name="prices[${locationId}][minday]" id="minday-${locationId}" placeholder="最少租赁天数"> </div> <div class="form-group"> <label for="saleprice-${locationId}">促销价格</label> <input type="text" class="form-control" name="prices[${locationId}][saleprice]" id="saleprice-${locationId}" placeholder="促销价格"> </div> <div class="form-group"> <label for="mindaystay-${locationId}">最短停留天数</label> <input type="text" class="form-control" name="prices[${locationId}][mindaystay]" id="mindaystay-${locationId}" placeholder="最短停留天数"> </div> </div> </div> </div> ` document.getElementById('price-container').insertAdjacentHTML('beforeend', blockHtml) } else { // 取消勾选时移除对应区块 const block = document.getElementById(priceBlockId) if (block) block.remove() } }) })
第三步:后端接收说明
提交后可在控制器中直接通过$request->prices获取所有选中位置的价格数组,遍历存入price表即可,完美适配Car和Price的hasMany关联。
内容的提问来源于stack exchange,提问作者Mhamad Abu AlGhanam
相关产品推荐
相关产品推荐

