Laravel 动态依赖下拉菜单
Posted
技术标签:
【中文标题】Laravel 动态依赖下拉菜单【英文标题】:Laravel Dynamic Dependent Dropdown Menu 【发布时间】:2021-05-08 07:20:17 【问题描述】:我希望能够选择一种车辆类型并使用与该选择相关的价格将其添加到卡片中服务的基本价格中。我知道有很多示例可以更改第二个下拉菜单中的选项,经典的国家和州示例,但我似乎找不到任何使用所选菜单项的方式,我可以将其添加到服务价格。这是我到目前为止的代码:
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select vehicle type
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
@foreach($vehicles as $vehicle)
<a class="dropdown-item" href="#"> $vehicle->type </a>
@endforeach
</div>
</div>
</div>
@foreach($services as $service)
<div class="card mt-3">
<div class="card-body">
<div class="d-flex justify-content-between">
<h4 class="card-title"> $service->nom </h4>
--this is where I'd like to use the selected vehicle type to simply add it to
the service price. If i do: $service->price + $vehicle->price it chooses
the last one that went through the foreach loop --
<h3> $service->price $</h3>
</div>
<p class="card-text"> $service->description </p>
</div>
</div>
@endforeach
我知道这不是很花哨(或很好)的编程,但我已经坚持了好几个小时。我也知道我需要一个脚本来使其真正动态化,并且很可能使用表单来选择车辆类型。
【问题讨论】:
所以基本上tabs? 【参考方案1】:<script>
function updateServicePrice(vehicle)
const vehiclePrice = Number(vehicle.dataset.price);
const services = Array.from(document.getElementsByClassName('service-price'));
services.forEach(service =>
service.innerhtml = Number(service.dataset.price) + vehiclePrice;
);
</script>
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select vehicle type
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
@foreach($vehicles as $vehicle)
<a onclick="updateServicePrice(this)" data-price=" $vehicle->price " class="dropdown-item" href="#"> $vehicle->type </a>
@endforeach
</div>
</div>
</div>
@foreach($services as $service)
<div class="card mt-3">
<div class="card-body">
<div class="d-flex justify-content-between">
<h4 class="card-title"> $service->nom </h4>
--this is where I'd like to use the selected vehicle type to simply add it to
the service price. If i do: $service->price + $vehicle->price it chooses
the last one that went through the foreach loop --
<h3 class="service-price" data-price=" $service->price "> $service->price $</h3>
</div>
<p class="card-text"> $service->description </p>
</div>
</div>
@endforeach
【讨论】:
谢谢你,不知道你可以那样做。你是救生员! 您知道为什么在尝试使用选择以显示按钮下拉菜单中的选择时它不起作用吗? 当您的Larael代码产生结果时,您没有任何选择的车辆,因此您无法计算价格,因此您需要监听车辆选择并更新价格。如果您想在客户端不使用脚本完成所有工作,那么您应该使用a
或 form
提交您选择的车辆,并使用 Laravel 的模板引擎构建具有计算价格的新页面以上是关于Laravel 动态依赖下拉菜单的主要内容,如果未能解决你的问题,请参考以下文章