Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 558
ivan.mylyanyk Avatar asked Apr 07 '15 09:04

ivan.mylyanyk


1 Answers

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

like image 110
ivan.mylyanyk Avatar answered Sep 20 '22 19:09

ivan.mylyanyk