[英]Select2 remote data with pre selected value
I want to load select2 remote data and also with some selected value.我想加载 select2 远程数据以及一些选定的值。
My code is like this我的代码是这样的
$("#category_input").select2({
dropdownParent: $("#changeCategoryModal"),
placeholder: "Change Category",
closeOnSelect: false,
maximumSelectionLength: 3,
ajax: {
url: url,
dataType: 'json',
processResults: function(response) {
return {
results: response,
};
}
}
});
If I want to make id 1,2,3 (Example) selected, What can I do here?如果我想选择 id 1,2,3(示例),我可以在这里做什么?
(I am using this script in Laravel blade template) (我在 Laravel 刀片模板中使用此脚本)
If I understand your query correct, you can try this below approach.如果我理解您的查询正确,您可以尝试以下方法。
Approach:方法:
controller.php controller.php
public function fetch_data()
{
if(request()->ajax()) {
//process your data and logics
//here is some sample data to understand the flow
$selected_options = array(1, 3);
$data = array(['id' => 1, 'name' => 'produc1'], ['id' => 2, 'name' => 'produc2'], ['id' => 3, 'name' => 'produc3']);
return view('select2', compact('selected_options', 'data'))->render();
}
}
select2.blade.php select2.blade.php
@foreach($data as $key => $val)
<option value="{{$val['id']}}" @if(in_array($val['id'], $selected_options)) selected @endif> $val['name'] </option>
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.