📜  jquery select2 多选全选 - Javascript (1)

📅  最后修改于: 2023-12-03 15:32:09.754000             🧑  作者: Mango

jQuery Select2 多选全选 - Javascript

Select2 是一个基于 jQuery 的选择性搜索框,具有自动完成文本框,搜索框,下拉框和分页等功能。而当需要在多选 Select2 中添加“全选”功能时,引入Select2官方提供的插件 select2-plugin-i18n,便可以轻松地实现。

示例
<!DOCTYPE html>
<html>
<head>
    <title>Select2 多选全选示例</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" />
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/i18n/zh-CN.js"></script>
</head>
<body>
    <select id="mySelect" multiple="multiple" style="width: 100%">
        <option value="1">苹果</option>
        <option value="2">香蕉</option>
        <option value="3">橙子</option>
        <option value="4">西瓜</option>
    </select>

    <script>
        $(document).ready(function() {
            $('#mySelect').select2({
                placeholder: '请选择水果',
                language: 'zh-CN',
            });
            $('#mySelect').on('select2:select', function(e) {
                var data = e.params.data;
                if (data.id === 'selectAll') {
                    $(this).find('option').prop('selected', true);
                    $(this).trigger('change');
                }
            });
            $('#mySelect').prepend('<option id="selectAll" value="selectAll">全选</option>');
            $('#mySelect').val(['selectAll']).trigger('change');
        });
    </script>
</body>
</html>
解释

这个示例主要的 JS 代码如下:

$(document).ready(function() {
    $('#mySelect').select2({
        placeholder: '请选择水果',
        language: 'zh-CN',
    });
    $('#mySelect').on('select2:select', function(e) {
        var data = e.params.data;
        if (data.id === 'selectAll') {
            $(this).find('option').prop('selected', true);
            $(this).trigger('change');
        }
    });
    $('#mySelect').prepend('<option id="selectAll" value="selectAll">全选</option>');
    $('#mySelect').val(['selectAll']).trigger('change');
});

首先,我们初始化了 select2,其中设置了 placeholder 和语言。接下来,我们为 select2 绑定了一个 select2:select 事件,当选择了“全选”时,将所有 option 的 selected 属性设为 true,并触发 change 事件。最后,我们在 select2 的第一项添加了“全选”选项,并指定它的 id 为“selectAll”。最后,我们将“全选”选项设为选中状态,以便默认选中。

结论

通过这个示例,可以看出通过引入 select2-plugin-i18n 插件,我们可以很容易地为 Select2 添加“全选”功能。同时,我们也熟悉了在 jQuery 中为 Select2 绑定事件并修改属性的方法。