I want to load select2 remote data and also with some selected value.
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?
(I am using this script in Laravel blade template)
If I understand your query correct, you can try this below approach.
Approach:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.