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?
Adding the following is enough: . select2-container . select2-choice { height: 200px; } To have it apply only after an object is selected, add/modify the corresponding css on a change event or similar. This changes the height of the select2 input field, which is not what was asked for.
// Set up the Select2 control $('#mySelect2').select2({ ajax: { url: '/api/students' } }); // Fetch the preselected item, and add to the control var studentSelect = $('#mySelect2'); $.ajax({ type: 'GET', url: '/api/students/s/' + studentId }).then(function (data) { // create the option and append to Select2 var option ...
In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This has been replaced by the current method on the data adapter. AMD Modules: select2/compat/initSelection"
The dropdownParent option allows you to pick an alternative element for the dropdown to be appended to: $('#mySelect2').select2({ dropdownParent: $('#myModal') }); This is useful when attempting to render Select2 correctly inside of modals and other small containers.
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" ...>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With