jQuery – 好用的外掛 select2。介紹AJAX方法。

安裝

可以使用 NPM 安裝,用 Webpack 執行。以下介紹簡單傳統用法。

加入 jQuery 與 select2

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Select2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<!-- Select2 i18 中文翻譯 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/i18n/zh-TW.js"></script>

 

npm

npm i select2

 

基本用法

<option> 外層不一定要使用 <optgroup> 做分類

<form method="post">
    <select class="user">
        <optgroup label="admin">
            <option value="1">Blue</option>
            <option value="2">David</option>
        </optgroup>
        <optgroup label="guest">
            <option value="1">Judy</option>
            <option value="2">Kate</option>
            <option value="2">John</option>
        </optgroup>
    </select>
</form>
$(function (){
    $(".user").select2({
        language: 'zh-TW',
        width: '100%',
        // 最多字元限制
        maximumInputLength: 10,
        // 最少字元才觸發尋找, 0 不指定
        minimumInputLength: 0,
        // 當找不到可以使用輸入的文字
        tags: true,
    });
})

 

動態定義 option

data 的部分可以透過 AJAX 取得以後,再渲染 <option>。

<form method="post">
    <select class="user"></select>
</form>
$(function (){
    $(".user").select2({
        language: 'zh-TW',
        width: '100%',
        // 最多字元限制
        maximumInputLength: 10,
        // 最少字元才觸發尋找, 0 不指定
        minimumInputLength: 0,
        // 當找不到可以使用輸入的文字
        tags: true,
        data: [
            { 
                text: "admin", 
                children : [
                    { id: 1, text: "Blue" },
                    { id: 2, text: "David"}
                ]
            },
            { 
                text: "guest", 
                children : [
                    { id: 3, text: "Judy" },
                    { id: 4, text: "Kate" },
                    { id: 5, text: "John" },
                ]
            }
        ],
    });
})

上面示範有使用 <optgroup> 的作法,如果不需要分類就直接

...
data: [
    { id: 1, text: "Blue" },
    { id: 2, text: "David"},
    { id: 3, text: "Judy" },
    { id: 4, text: "Kate" },
    { id: 5, text: "John" },
]

要給 <option> 的格式,務必要包含 id, text 兩個參數。

AJAX

當搜尋的時候,才開始向伺服器要資料,並呈現再 <option>

<form method="post">
    <select class="user"></select>
</form>
$(function (){
    $(".user").select2({
        language: 'zh-TW',
        width: '100%',
        // 最多字元限制
        maximumInputLength: 10,
        // 最少字元才觸發尋找, 0 不指定
        minimumInputLength: 0,
        // 當找不到可以使用輸入的文字
        // tags: true,
        placeholder: '請輸入名稱...',
        // AJAX 相關操作
        ajax: {
            url: 'https://next.json-generator.com/api/json/get/E1SKlb7-r',
            type: 'get',
            // 要送出的資料
            data: function (params){
                // 在伺服器會得到一個 POST 'search' 
                return {
                    search: params.term 
                };
            },
            processResults: function (data, params){
                console.log(data)

                // 一定要返回 results 物件
                return {
                    results: data,
                    // 可以啟用無線捲軸做分頁
                    pagination: {
                        more: true
                    }
                }
            }
        }
    });
})

processResults 從伺服器取得的結果,因為 return.results 要產生 <option> ,所以記得格式務必為

[
    { id: 1, text: "Blue" },
    ......
]

 

複選

<select> 改為複選之外,select2 也要添加 tags: true。

<form method="post">
    <select class="user" name="user[]" multiple></select>
</form>
$(function (){
    $(".user").select2({
        language: 'zh-TW',
        width: '100%',
        // 最多字元限制
        maximumInputLength: 10,
        // 最少字元才觸發尋找, 0 不指定
        minimumInputLength: 0,
        // 當找不到可以使用輸入的文字
        tags: true,
        data: [
            { id: 1, text: "Blue" },
            { id: 2, text: "David"},
            { id: 3, text: "Judy" },
            { id: 4, text: "Kate" },
            { id: 5, text: "John" }
        ],
    });
})

 

AJAX 預選

從遠端取得資料後,只需要對綁定的元素使用 jQuery 的 apeend() 與 trigger() 觸發就可以了。

<form method="post">
    <select class="user" multiple></select>
</form>
$(function (){
    $user = $(".user");

    $user.select2({
        language: 'zh-TW',
        width: '100%',
        // 最多字元限制
        maximumInputLength: 10,
        // 最少字元才觸發尋找, 0 不指定
        minimumInputLength: 0,
        // 當找不到可以使用輸入的文字
        tags: true,
        data: [
            { id: 1, text: "Blue" },
            { id: 2, text: "David"},
            { id: 3, text: "Judy" },
            { id: 4, text: "Kate" },
            { id: 5, text: "John" }
        ],
    });

    // 取得預選的遠端資料
    $.get({
        url: 'https://next.json-generator.com/api/json/get/NkjWQg4bS',
        success: function (obj){
            // obj = [{"id": 3,"text": "Judy"},{"id": 4, "text": "Kate"},{"id": 100, "text": "Jason"}]
            $.each(obj, function(index, ele) {
                // Jason 因為原本資料不存在,所以會被加入,其他則僅是替換
                var option = new Option(ele.text, ele.id, true, true);
                $user.append(option).trigger('change');
            });
        }
    }, "json")
})

 

Select2 相關設定可以參考官方

Comments

  1. 十分感谢

發表迴響