我有两个多选下拉列表。我想根据第一个多重选择下拉列表填充第二个多重选择下拉列表。
web.php
Route::get('allstate/{id}', 'LocationController@allstate');
国家/地区下拉菜单(第1个)
<select multiple="multiple" name="country[]" id="country" class="select">
@foreach($country_data as $country)
<option value="{{$country->country_id}}" >
{{$country->country_name}}</option>
@endforeach
</select>
状态下拉列表(第二个)
<select multiple="multiple" name="city[]" id="city" class="select">
</select>
控制器
public function index()
{
$country_data=DB::table('country')->select('country_id','country_name')->orderby('country_name')->get();
return view('location',compact('country_data') );
}
public function allstate($id)
{
$state_data= DB::table('state')->whereIn('country_id',$id)->select('state_id','state_name')->get();
return json_encode($caste_data);
}
脚本
<script type="text/javascript">
$(document).ready(function() {
$('select[name="country[]"]').on('change', function() {
var countryID = $(this).val();
if(countryID) {
$.ajax({
url: 'allstate/'+countryID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="city[]"]').empty();
$.each(data, function(key, value) {
$('select[name="city[]"]').append('<option value="'+ value.city_id +'">'+ value.city_name +'</option>');
});
}
});
}else{
$('select[name="city[]"]').empty();
}
});
});