Limit the jQuery select2 maximum selected options

Faizan picture Faizan · Nov 5, 2013 · Viewed 11.5k times · Source

I have referred to this docs provided by select2 jQuery plugin. http://ivaynberg.github.io/select2/

But when I use this code to limit the number of options a user can select at a time:

$(document).ready(function(){
    $(".select2").select2({ maximumSelectionSize: 2 });
    });

And here is the html of select tag:

  <select id="store-name" name="state[]" class="select2-select-00 span6" multiple size="5"
            data-placeholder="Store" style="height:25px;">


        <?php foreach ($this->Store->get_all_stores_names() as $row) {

        //print_r($row);
          echo '<option value="' . $row->name . '"> ' . $row->name . '</option>';
        }
        ?>

    </select>

When I try to limit it, I get this error in console:

Uncaught TypeError: Object [object Object] has no method 'select2'

Why? I mean the select2 works fine which means that it's js files are being loaded, then why I am unable to limit it?

Answer

Yevgeniy Afanasyev picture Yevgeniy Afanasyev · Jan 14, 2016

Use maximumSelectionLength like so:

$("#selectQQQ").select2({
    maximumSelectionLength: 3
});

Extension

Select2 has data-* attributes

Meaning, that you can set your maximumSelectionLength parameter as HTML5 data attributes like so:

<select data-placeholder="Select a state" data-maximum-selection-length="2" ...>