我正试图获得动态下拉与Laravel和Select2工作。有两个下拉菜单;一个是公司,比如。"company2"answers"1"表示属于该公司的地点,即:"location2"。
对于我的生活,我不知道如何使"company2"下拉触发一个事件来读取该公司的位置,如果它被更改!我在这段代码的javascript部分做错了什么!(一切正常)
路线Route::controller('api', 'ApiController');
控制器(ApiController)
public function getLocations($companyId)
{
return Location::where('company_id', $companyId)->lists('id', 'name');
}
地址"api/locations/7"的输出示例
{"Yellowstone":"8"}
View (form open/close section省略)
{!! Form::select('company_id', $companies, null, ['class' => 'company2 form-control']) !!}
{!! Form::select('location_id', $locations, null, ['class' => 'location2 form-control']) !!}
视图(Javascript)
<script type="text/javascript">
$(document).ready(function() {
$(".company2").select2();
$(".location2").select2();
});
$(".company2").select2().on('change', function() {
var $company2 = $('.company2');
$.ajax({
url:"../api/locations/" + $company2.val(),
type:'GET',
success:function(data) {
var $location2 = $(".location2");
$location2.empty();
$.each(data, function(value, key) {
$location2.append($("<option></option>").attr("value", value).text(key));
});
$location2.select2();
}
});
}).trigger('change');
</script>
初始化时,向视图传递一个活动公司列表,即
$companies = Company::lists('trading_name', 'id');
用下面的代码替换你的javascript,你可能需要调整其中的一些。请务必仔细阅读评论
var $company2 = $('.company2');
var $location2 = $(".location2");
$company2.select2().on('change', function() {
$.ajax({
url:"../api/locations/" + $company2.val(), // if you say $(this) here it will refer to the ajax call not $('.company2')
type:'GET',
success:function(data) {
$location2.empty();
$.each(data, function(value, key) {
$location2.append($("<option></option>").attr("value", value).text(key)); // name refers to the objects value when you do you ->lists('name', 'id') in laravel
});
$location2.select2(); //reload the list and select the first option
}
});
}).trigger('change');
从控制器获取位置数据时更改以下内容
public function getLocations($companyId)
{
return Location::where('company_id', $companyId)->lists('name', 'id');
}
你可以试试:
$.getJSON("getOptions.php", function (json) {
$("#inputs").select2({
data: json,
width: "180px"
});
});
输出示例:
{id:0,text:"Text 1"},
{id:1,text:"Text 2"},
{id:2,text:"Text 3"},
{id:3,text:"Text 4"},
{id:4,text:"Text 5"}