0%

specific search word in select2

specific search word after selector open

data source: ajax

  1. create a select2 selector and initial it
1
<select id="selector" isvalid="yes" autocomplete="off"></select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
var globalKeyword = '';
$('#selector').select2({
placeholder: 'please input keyword',
//set this selector multiple, or we cant find that input element, dont know why
multiple: true,
maximumSelectionLength: 1,
allowClear: true,
ajax: {
type: 'POST',
url: 'your data source url',
dataType: 'json',
contentType : 'application/json',
//load options page by page, you can ignore from here to line 43, just fill the selector with all options
data: function(params){
if(params.term == null){
params.term = '';
}
//save keyword
globalKeyword = params.term;
//search by multi keyword
var keyword = params.term.split(/\s+/);
var param = {
name: keyword,
pageNumber: params.page || 1,
pageSize: 10,
sortOrder: "asc",
};
return JSON.stringify(param);
},
processResults: function(r, params) {
params.page = params.page || 1;
var itemList = [];
$.each(r.rows, function(idx, item) {
itemList.push({id: item.id, text: item.name});
});
return {
results: itemList,
pagination: {
more: r.pageNo<r.totalPages
}
}
},
cache: true,
},
minimumInputLength: 0
});

//clear selected option
$('#selector').val('').trigger('change');
//save keyword here or it will be clear after selector open again
var keyword = globalKeyword;
//dropdown selector
$('#selector').select2('open');
//set keyword
$('.select2-search__field').val(keyword);