maximumSelectionSize isn't working in Select2

被刻印的时光 ゝ 提交于 2019-12-08 19:39:32

问题


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

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
    });
});

My html selectbox:

<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/

What is wrong with this chunk of code?


回答1:


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

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

$(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

Everything works like a charm:

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

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/.



来源:https://stackoverflow.com/questions/29487957/maximumselectionsize-isnt-working-in-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!