maximumSelectionSize在Select2中不起作用 [英] maximumSelectionSize isn't working in Select2

查看:567
本文介绍了maximumSelectionSize在Select2中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多值选择,我想使用 select2 库设置所选项目数量的限制。

I have a multivalue select, and I want to set the restriction on number of selected items using the select2 library.

文档说我应该设置 maximumSelectionSize 在对象初始化期间。不幸的是,以下代码不起作用:

Documentation says that I should set maximumSelectionSize during the object initialization. Unfortunately, the following code doesn't work:

$(document).ready(function () {
    $("#select_demo").select2({
        maximumSelectionSize: 3
    });
});

我的html选择框:

<div class="form-group">
    <select id="select_demo" multiple="multiple" class="form-control select2 select2-container-multi">
        <optgroup label="One">
            <option>one</option>
            <option>two</option>
            <option>three</option>
            <option>four</option>
        </optgroup>
        <optgroup label="Two">
            <option>one2</option>
            <option>two2</option>
        </optgroup>
        <optgroup label="Three">
            <option>one3</option>
            <option>two3</option>
            <option>three3</option>
            <option>four3</option>
        </optgroup>
    </select>
</div>

http://jsfiddle.net/x4oqL1jr/2/

这段代码有什么问题?

推荐答案

由于 select2 版本4.0 ,他们已经替换了 maximumSelectionSize maximumSelectionLength

Since the version 4.0 of select2 they have replaced maximumSelectionSize with maximumSelectionLength.

所以,只需更改 js 代码的方式如下:

So, just change the js code in the following way:

$(document).ready(function () {
    $("#select_demo").select2({
        maximumSelectionLength: 3
    });
});

您可以在此链接后找到最新文档: https://select2.github.io/examples.html#multiple-max

You can find the latest documentation following this link: https://select2.github.io/examples.html#multiple-max

一切都像魅力一样:

http://jsfiddle.net/4tk4hymn/1/

更新:您还可以添加 data-maximum-selection-length =3属性,如注释中所指出。例如,请参阅 http://jsfiddle.net/1b8y9uzh/

UPDATE: You can also add a data-maximum-selection-length="3" attribute as pointed out in the comments. For example, see http://jsfiddle.net/1b8y9uzh/.

这篇关于maximumSelectionSize在Select2中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆