根据 laravel 中的另一个下拉列表选定值填充下拉列表 - 编辑表单

Populate dropdown based on another dropdown selected value in laravel - edit form

我在另一个网站上找到了完成此操作的方法,并且成功了。我的问题是我需要在我的编辑表单中使用它(最好使用与我的创建表单相同的表单,因为我的创建和编辑视图使用相同的表单)。当我转到我的编辑页面时,"Section" 下拉值被选中,因为它应该是。但是 "Subsection" 不是,因为当然我没有点击它。可能这是一个对我来说太容易看到的修复,但我对 javascript 不太满意。我基本上需要第二个下拉菜单(第一个小节)来显示正确的选项,在我的编辑视图中,根据选择 "section"(第一个下拉菜单)显示正确的选项。

剖面模型:

public function subsections()
{
    return $this->hasMany('App\Subsection');
}

分段模型:

public function section()
{
    return $this->belongsTo('App\Section');
}

查看:

{!! Form::select('section_id', [null=>'-- Select Section --'] + $sections, null, array('id' => 'section')) !!}

<select id="subsection" name="subsection_id" class="select">
    <option>-- First Select Section --</option>
</select>

From my controller: $sections = Section::lists('section', 'id');

脚本:

<script>
$(document).ready(function($){
    $('#section').change(function(){
        $.get("{{ url('api/dropdown')}}", 
        { option: $(this).val() }, 
        function(data) {
            $('#subsection').empty(); 
            $.each(data, function(key, element) {
                $('#subsection').append("<option value='" + key +"'>" + element + "</option>");
            });
        });
    });
});
</script>

路线:

Route::get('api/dropdown', function(){
    $id = Input::get('option');
    $subsections = Section::find($id)->subsections;
    return $subsections->lists('subsection', 'id');
});

如果你只想select jquery中的第一个选项,你可以添加:

$('#subsection option:eq(1)').prop('selected', true);

否则,如果您想 select 一个特定的值,您可以通过

$('#subsection option[value="value_to_be_selected"]').prop('selected', true);

在将所有值附加到小节后使用它

在我的控制器中我添加了:

    $subsections = Subsection::where('section_id', '=', $transaction->section_id)->orderBy('subsection', 'asc')->lists('subsection', 'id');

在我看来我是这样做的:

    @if(isset($transaction))
    {!! Form::select('subsection_id', [null=>'-- Select Subsection --'] + $subsections, null, array('class' => 'select', 'id' => 'subsection')) !!}
    @else
        <select id="subsection" name="subsection_id" class="select">
            <option>-- First Select Section --</option>
        </select>
    @endif

问题已解决:)

所以,我们要做的是首先将值发送到依赖下拉列表,如
"<option value="">Select Something</option>" 当 return 出错时创建完整的下拉菜单并选择以下值和 return,这将减少很多 javascript 调用。
控制器:

if($error){
//create get array of second drop-down, suppose $second_drop
// create complete second drop-down like
$selectbox="";
foreach($second_drop as $option){
            $selectbox.="<option value='". $option->id."'";
            if($request->option2==$ $option->id){
                $selectbox.=" selected ";
            }

            $selectbox.=">".$option->value."</option>";
        }
}
return view('routename', ['selectbox2' =>   $selectbox]);

查看:

<select id="subsection" name="subsection_id" class="select">
    {!! $selectbox !!}
</select>