1. 程式人生 > >十一、select2實現下拉選單

十一、select2實現下拉選單

html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="/static/js/jquery-2.1.0.js"></script>
    <link rel="stylesheet" href="/static/css/select2.min.css">
    <script type="text/javascript" src="/static/js/select2.full.js"
>
</script> <script type="text/javascript" src="/static/js/json2.js"></script> </head> <body> <div> <div class="mycontainer"> <table width="50%"> <tr> <td width="50%">組: <select
id="group" name="group" style="width: 70%">
</select> </td> <td width="=50%">成員: <select id="tester" name="tester" style="width: 70%"> </select> </td
>
</tr> </table> </div> </div> </body> </html>

javascript:

<script>
$('#group').select2({
    placeholder: 'select a group',
    ajax: {
        url: "/group",
        dataType: 'json',
        processResults: function(data) {
            return {
                results: $.map(data, function(item) {
                    return {
                        text: item.text,
                        id: item.id
                    }
                })
            };
        },
    }
});

$('#tester').select2({
    placeholder: 'select a tester'
}); 

// group被選擇時,tester從後臺獲取資料並展示到前端
$('#group').on('select2:select', function(evt) {
    //清空select2的options
    $("#tester").empty();
    $('#tester').select2({
        placeholder: 'select a tester',
        ajax: {
            url: "/tester",
            type: 'get',
            dataType: 'json',
            data: {
                'group': $("#select2-group-container").html()
            },
            processResults: function(data) {
                return {
                    results: $.map(data, function(item) {
                        return {
                            text: item.text,
                            id: item.id
                        }
                    })
                };
            },
        }
    });
});
</script>

效果如下:
下拉選單效果圖