【发布时间】:2018-03-29 04:15:41
【问题描述】:
我的目标是实现一个动态下拉菜单,该下拉菜单将根据第一个下拉菜单显示第二个下拉菜单的值。
一个服务有很多类别,一个类别属于一个服务,所以第二个下拉列表是类别,第一个下拉列表是服务。选择服务后,它将根据所选服务显示所有类别。
这是 RequestController.php
中的代码public function create()
{
$client = Client::all()->sortBy('client_name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('client_name', 'id');
$services = Service::with('categories')->get()->sortBy('code', SORT_NATURAL | SORT_FLAG_CASE)->pluck('description', 'id');
$categories = Categories::with('service')->get()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('name', 'id');
return view('encoder-dashboard.analysis-request.create', compact('client', 'services', 'categories'));
}
在我的 fields.blade.php
<!-- Service Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('service_id', 'Service:') !!}
{!! Form::select('service_id', $services, null, ['class' => 'form-control','required'])!!}
</div>
<!-- Categories Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('category_id', 'Category:') !!}
{!! Form::select('category_id', $categories, null, ['class' => 'form-control','required'])!!}
</div>
处理请求的脚本
<script>
$(function() {
$('select[name=service_id]').change(function() {
var url = '{{ url('service') }}' + $(this).val() + '/categories/';
$.get(url, function(data) {
var select = $('form select[name= category_id]');
select.empty();
$.each(data,function(key, value) {
select.append('<option value=' + value.id + '>' + value.name + '</option>');
});
});
});
});
</script>
路由web.php
Route::get('service/{service}/categories', 'ServiceController@getCategories');
而在ServiceController.php
public function getCategories($service)
{
$service = Service::findOrFail($service);
return $service->categories->pluck(['id','name']);
}
我实现了使用 pluck 获取所有数据。但是名称为 category_id
的类别的表单为空所以我猜我的问题是在脚本内还是不?
如果有人可以提供帮助,我们将不胜感激。 提前致谢。
【问题讨论】: