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?

Community
  • 1
  • 1
ivan.mylyanyk
  • 2,051
  • 4
  • 30
  • 37

1 Answers1

21

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

ivan.mylyanyk
  • 2,051
  • 4
  • 30
  • 37
  • is it possible to add data-maximumSelectionLength="2" ? – Abhi Burk Feb 07 '19 at 05:41
  • @AbhiBurk I just tried to modify the fiddle above, and seems like it doesn't work, unfortunately. For example: http://jsfiddle.net/wz2qLj9k/ – ivan.mylyanyk Feb 07 '19 at 22:39
  • 1
    It should be like this data-maximum-selection-length="2. – Abhi Burk Feb 08 '19 at 02:06
  • 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 }); – Jp Silver Nov 27 '20 at 15:23