maximumSelectionSize isn't working in Select2
Asked Answered
R

1

9

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?

Repeated answered 7/4, 2015 at 9:15 Comment(0)
R
23

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

Repeated answered 7/4, 2015 at 9:15 Comment(4)
is it possible to add data-maximumSelectionLength="2" ?Berna
@AbhiBurk I just tried to modify the fiddle above, and seems like it doesn't work, unfortunately. For example: jsfiddle.net/wz2qLj9kRepeated
It should be like this data-maximum-selection-length="2.Berna
Nope still not working.... $("#affected").select2({ tags: true, selectOnBlur: true, maximumSelectionLength: 1 }).on("change", function(e) { var obj = $($("#affected").select2().find(":selected")[0]); if(obj === undefined) return; console.log(obj.attr("data")); $("#tv_id").val(obj.attr("data")); }); $("#affected").select2({ tags: true, selectOnBlur: true, maximumSelectionLength: 1 });Bludgeon

© 2022 - 2024 — McMap. All rights reserved.