我在Laravel5.4视图中有这样一个表格:
<form action="#" method="POST" class="form-inline" role="form">
{{ csrf_field() }}
<div class="form-group">
<select id="tdcategory" class="selectpicker show-tick show-menu-arrow" onchange="this.form.submit()">
@foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
@endforeach
</select>
</div>
<div class="form-group">
<select id="tdlocation" class="selectpicker show-tick show-menu-arrow" onchange="this.form.submit()">
@foreach($locations as $location)
<option value="{{ $location->id }}">{{ $location->name }}</option>
@endforeach
</select>
</div>
</form>
我有两个问题:
1)如何动态地将表单操作设置为
categories/{category->id}/locations/{location->id}
其中,类别->id和位置->id都将基于用户当前选择的选项的值。
2)由于表单是在用户更改选项时提交的,因此页面将重新加载并重置两个<select>
标记。如何跟踪以前选择的选项,并且在页面加载时,我可以在表单提交之前向用户显示他/她选择了哪一个?
发布于 2017-04-16 20:34:36
1)您可以通过JS:从select中删除"onchange“属性,并添加inital代码,如下所示:
$('#tdcategory,#tdlocation').change(function(){
var category = $('#tdcategory').val();
var location = $('#tdlocation').val();
if (category && location) {
$(this).closest('form')
.attr('action', '/categories/'+ category +'/locations/' + location)
.submit();
}
});
2)您可以从请求中获取提交的值,并在每个select中添加一个将selected="selected“属性插入的条件,如下所示:
<select id="tdcategory" name="tdcategory" class="selectpicker show-tick show-menu-arrow">
@foreach($categories as $category)
<option value="{{ $category->id }}" @if($category->id == request()->get('tdcategory'))selected="selected"@endif>{{ $category->name }}</option>
@endforeach
</select>
<select id="tdlocation" name="tdlocation" class="selectpicker show-tick show-menu-arrow">
@foreach($locations as $location)
<option value="{{ $location->id }}" @if($location->id == request()->get('tdlocation'))selected="selected"@endif>{{ $location->name }}</option>
@endforeach
</select>
https://stackoverflow.com/questions/43438462
复制