Javascript 选择2设置选定的不使用分页选项
我使用了select2分页 以下是我的javascript代码:Javascript 选择2设置选定的不使用分页选项,javascript,jquery,jquery-select2,Javascript,Jquery,Jquery Select2,我使用了select2分页 以下是我的javascript代码: $("#propinsi").select2({ width: "100%", placeholder: "Provinsi", ajax: { url: "{{ route('propinsi') }}", dataType: "json", data: func
$("#propinsi").select2({
width: "100%",
placeholder: "Provinsi",
ajax: {
url: "{{ route('propinsi') }}",
dataType: "json",
data: function (params) {
return {
term: params.term || '',
page: params.page || 1,
page_limit: 10,
};
}
// cache: true
}
});
然后传递到控制器上的方法:
public function provinsi($page, $term, $page_limit, $kode_negara){
$offset = ($page - 1) * $page_limit;
$result = [];
$query = DB::table('m_wilayah_provinsi')->where(function($query) use ($kode_negara) {
$query->where('id_negara', $kode_negara);
})->select('id AS id', 'provinsi AS text');
// if (!empty($term)) {
// $query->where('provinsi', 'like', '%'.$term.'%');
// }
$count = $query->count();
$endCount = $offset + $page_limit;
$morePages = $count > $endCount;
$query = $query->skip($offset)->take($page_limit)->get();
$result = [
'results' => $query,
'pagination' => [
'more' => $morePages
]
];
return response()->json($result);
}
用于显示json数据的功能正常,但我无法设置为selected
我尝试过这样设置,但仍然不起作用:
$("#propinsi").val(1).trigger("change");
及
有人能帮我吗 试试这个:
$("#propinsi").select2('data', {id: 100, a_key: 'Lorem Ipsum'});
但是如果我使用这种方法,select2上的分页将不起作用,你知道吗?因此,最好的解决方法是简单地将预选项添加为新选项。
$("#propinsi").select2('data', {id: 100, a_key: 'Lorem Ipsum'});