[英]Populate dropdown based on another dropdown selected value in laravel - edit form
我发现如何在另一个网站上实现这一点,我得到了它的工作。 我的问题是我需要在我的编辑表单中使用它(最好使用与我的创建表单相同的表单,因为我的创建和编辑视图使用相同的表单)。 当我转到我的编辑页面时,应该选择“部分”下拉值。 但“分段”不是,因为我没有点击它。 可能这对我来说太容易了,但我对javascript不太满意。 我基本上需要第二个下拉列表(第一个小节),根据我的编辑视图中选择的“部分”(第一个下拉列表)显示正确的选项。
部分型号:
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');
});
如果您只想在jquery中选择第一个选项,可以添加:
$('#subsection option:eq(1)').prop('selected', true);
或者如果你想选择一个特定的值,你可以这样做
$('#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>"
并在返回错误时创建完整的下拉列表并选择以下值并返回, 这将减少大量的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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.