简体   繁体   English

maximumSelectionSize在Select2中不起作用

[英]maximumSelectionSize isn't working in Select2

I have a multivalue select, and I want to set the restriction on number of selected items using the select2 library. 我有一个多值选择,我想使用select2库设置所选项目数量的限制。

Documentation says that I should set maximumSelectionSize during the object initialization. 文档说我应该在对象初始化期间设置maximumSelectionSize Unfortunately, the following code doesn't work: 不幸的是,以下代码不起作用:

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

My html selectbox: 我的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/ http://jsfiddle.net/x4oqL1jr/2/

What is wrong with this chunk of code? 这段代码有什么问题?

Since the version 4.0 of select2 they have replaced maximumSelectionSize with maximumSelectionLength . 由于4.0版本 select2 ,他们已经取代maximumSelectionSizemaximumSelectionLength

So, just change the js code in the following way: 所以,只需按以下方式更改js代码:

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

You can find the latest documentation following this link: https://select2.github.io/examples.html#multiple-max 您可以在以下链接中找到最新文档: https//select2.github.io/examples.html#multiple-max

Everything works like a charm: 一切都像魅力一样:

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

UPDATE: You can also add a data-maximum-selection-length="3" attribute as pointed out in the comments. 更新:您还可以添加data-maximum-selection-length="3"属性,如注释中所指出的那样。 For example, see http://jsfiddle.net/1b8y9uzh/ . 例如,请参阅http://jsfiddle.net/1b8y9uzh/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM