[英]select2 - combining getting remote data with muliple select and pre data
[英]Select2 remote data with pre selected value
我想加載 select2 遠程數據以及一些選定的值。
我的代碼是這樣的
$("#category_input").select2({
dropdownParent: $("#changeCategoryModal"),
placeholder: "Change Category",
closeOnSelect: false,
maximumSelectionLength: 3,
ajax: {
url: url,
dataType: 'json',
processResults: function(response) {
return {
results: response,
};
}
}
});
如果我想選擇 id 1,2,3(示例),我可以在這里做什么?
(我在 Laravel 刀片模板中使用此腳本)
如果我理解您的查詢正確,您可以嘗試以下方法。
方法:
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
@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.