Limit the jQuery select2 maximum selected options
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" ...>
Related videos on Youtube
Faizan
A computer science geek ! Portfolio I am a freelancer, web designer and front-end developer. Just say Hi ! www.faizanzahid.me
Updated on September 16, 2022Comments
-
Faizan almost 2 years
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?
-
Abhi Burk over 5 yearsis it possible to add data-maximumSelectionLength="2" ?
-
Yevgeniy Afanasyev over 5 years@AbhiBurk, is it not working? What is your error message?\
-
Abhi Burk over 5 yearsno error and it worked using this on an element
data-maximum-selection-length="2"
-
Yevgeniy Afanasyev over 5 yearsYou are right, I forget to put a data attribute way to set it in the answer. Thank you.