基于Laravel中所选选项的表单操作中的动态路径路径

时间:2017-04-16 14:49:38

标签: javascript forms laravel laravel-blade

我在laravel 5.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)如何将表单操作动态设置为

  

类别/ {类别 - &GT; ID} /位置/ {位置 - &GT; ID}

其中,category-&gt; id和location-&gt; id都将基于用户当前选择的选项的值

2)由于在用户更改选项时提交了表单,因此会重新加载页面并重置<select>标记。如何跟踪以前选择的选项,当页面加载时,我可以向用户显示他/她在提交表单之前选择了哪一个?

1 个答案:

答案 0 :(得分:1)

1)您可以通过JS执行此操作:从选择中删除“onchange”属性,并添加初始代码,如下所示:

$('#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)您可以从请求中获取提交的值,并为每个选择添加一个插入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>