Limit the jQuery select2 maximum selected options
Asked Answered
S

1

7

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?

Setiform answered 5/11, 2013 at 13:21 Comment(2)
I don't see the .select2 class in you htmlKoziol
I have even tried it with the id selector like this: jQuery("#store-name").select2({ maximumSelectionSize: 2 }); still same error.Setiform
C
7

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" ...>
Ceria answered 14/1, 2016 at 22:38 Comment(4)
is it possible to add data-maximumSelectionLength="2" ?Frond
@AbhiBurk, is it not working? What is your error message?\Ceria
no error and it worked using this on an element data-maximum-selection-length="2"Frond
You are right, I forget to put a data attribute way to set it in the answer. Thank you.Ceria

© 2022 - 2024 — McMap. All rights reserved.