Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
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
Tags
more
Archives
Today
Total
관리 메뉴

blog

[Select2] select2 적용하기 본문

Web/front-end

[Select2] select2 적용하기

hjkongkong 2022. 5. 30. 21:32

https://select2.org/getting-started/installation

CDN을 사용하면 편하지만 코드를 직접 다운로드받아서 사용도 가능하다.

https://github.com/select2/select2/releases/tag/4.1.0-rc.0

압축을 풀고, select2-4.1.0-rc.0\dist 내부의 데이터를 vender에 넣는다.

(vender는 플러그인을 모아놓은 폴더이다.)

 

1
2
3
<link href="../resources/vendor/select2/css/select2.min.css" rel="stylesheet">
 
<script src="../resources/vendor/select2/js/select2.min.js"></script>
cs

두 줄을 추가하면 설정 완료

1
2
3
4
5
6
7
<div class="selectboxtest-2">
    <select ID="select2_example">
        <option>Option1</option>
        <option>Option2</option>
        <option>Option3</option>
    </select>
</div>
cs

jsp

1
var _mSelect2 = $("#select_example").select2();
cs

js

확인


https://select2.org/data-sources/formats

이 형식으로 데이터를 받아와서 select2를 적용하려고한다.

1
2
3
4
5
<select id="select2_example"style="width: 300px">
    <option value="" disabled selected>Select your option</option>
</select>
 
 
cs

 

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
$(document).ready(function() {
 
    select_data = new Object();
 
    $.ajax({
        type: "GET",
        url: /*  https://select2.org/data-sources/formats의 포멧에 맞는 데이터 api 주소 */ ,
        dataType: "json",
        async: false,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert('통신 실패');
        },
        success: function(response) {
            select_data = response;
        }
    });
 
 
    $("#select2_example").select2({
        data: select_data.results,
        matcher: modelMatcher
    });
 
 
    function modelMatcher(params, data) {
 
        console.log(params);
        console.log(data);
        data.parentText = data.parentText || "";
 
        // Always return the object if there is nothing to compare
        if ($.trim(params.term) === '') {
            return data;
        }
 
 
        // Do a recursive check for options with children
        if (data.children && data.children.length > 0) {
            // Clone the data object if there are children
            // This is required as we modify the object to remove any non-matches
            var match = $.extend(true, {}, data);
 
            // Check each child of the option
            for (var c = data.children.length - 1; c >= 0; c--) {
                var child = data.children[c];
                child.parentText = data.parentText + " " + data.text;
 
                var matches = modelMatcher(params, child);
 
                // If there wasn't a match, remove the object in the array
                if (matches == null) {
                    match.children.splice(c, 1);
                }
 
            }
 
            // If any children matched, return the new object
            if (match.children.length > 0) {
                return match;
            }
 
            // If there were no matching children, check just the plain object
            return modelMatcher(params, match);
 
        }
 
        // If the typed-in term matches the text of this term, or the text from any
        // parent term, then it's a match.
 
        var original = (data.parentText + ' ' + data.text).toUpperCase();
        var term = params.term.toUpperCase();
 
        // Check if the text contains the term
        if (original.indexOf(term) > -1) {
            return data;
        }
 
 
        // If it doesn't contain the term, don't return anything
        return null;
 
    }
 
 
});
cs

참고 :

optgroup search - https://github.com/select2/select2/issues/3034

https://jsfiddle.net/shrpne/0qsoj5th/


api 구현

 

DB

 

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
@GetMapping("/optgroup")
 
public String selectByoptgroup() {
 
  // optgroup을 distinct로 select
  List < String > optgroupList = testRepo.selectDistinct();
 
  JSONObject returnObj = new JSONObject();
 
  JSONArray componentArray = new JSONArray();
 
  for (String optgroup: optgroupList) {
 
    JSONObject resultObj = new JSONObject();
 
    JSONArray childrenArray = new JSONArray();
 
    JSONObject resultChildren = new JSONObject();
 
    resultObj.put("text", optgroup);
 
    //optgroup으로 select
    List < String > temp = testRepo.selectByoptgroup(optgroup); 
 
    for (String text: temp) {
 
      JSONObject childrenObj = new JSONObject();
 
      childrenObj.put("id", text);
 
      childrenObj.put("text", text);
 
      childrenArray.add(childrenObj);
 
    }
 
    resultObj.put("children", childrenArray);
 
    componentArray.add(resultObj);
 
  }
 
  JSONObject pagination = new JSONObject();
 
  pagination.put("more"true);
 
  returnObj.put("pagination", pagination);
 
  returnObj.put("results", componentArray);
 
  return returnObj.toString();
 
}
cs