I have a question regarding select2. Is it possible that we will add "Select All" on the drop down itself?
Example:
<select>
<option value='-1'>select all</option>
<option value='a'>A</option>
<option value='b'>B</option>
<option value='c'>C</option>
</select>
When I choose "select all" the field will display "select all" but on the background the ac are selected.. it's seems like a trick.. hope you have a solution for this.
Thanks
Based on http://jsbin.com/seqonozasu/1/edit?html,js,output , you can do something like this:
$.fn.select2.amd.require([
'select2/utils',
'select2/dropdown',
'select2/dropdown/attachBody'
], function (Utils, Dropdown, AttachBody) {
function SelectAll() { }
SelectAll.prototype.render = function (decorated) {
var $rendered = decorated.call(this);
var self = this;
var $selectAll = $(
'<span class="select2-results__option select-all" aria-selected="false">Select All</span>');
$rendered.find('.select2-dropdown .select2-results').append($selectAll);
$selectAll.on('click', function (e) {
var $results = $rendered.find('.select2-results__option[aria-selected=false]:not(.select-all)');
// Get all results that aren't selected
$results.each(function () {
var $result = $(this);
// Get the data object for it
var data = $result.data('data');
// Trigger the select event
self.trigger('select', {
data: data
});
});
self.trigger('close');
});
$selectAll.on('mouseenter', function (e) {
var selectedClass = 'select2-results__option--highlighted';
var $results = $rendered.find('.select2-results__option[aria-selected=false]:not(.select-all)');
// Get all results that aren't selected
$results.each(function () {
var $result = $(this);
//remove selected class
$result.removeClass(selectedClass);
});
$(this).addClass(selectedClass);
});
$selectAll.on('mouseleave', function (e) {
var selectedClass = 'select2-results__option--highlighted';
$(this).removeClass(selectedClass);
});
return $rendered;
};
$("select").select2({
placeholder: "Select a User",
allowClear: true,
dropdownAdapter: Utils.Decorate(
Utils.Decorate(
Dropdown,
AttachBody
),
SelectAll
)
});
});
along with css:
span.select2-results__option.select-all {
display: block;
}
This adds all the selected elements to the select2 input.
To show "select all" rather than the element text, when you loop through the list elements on $selectAll.click()
, add them to an array rather than triggering the select
event, and then trigger the select
event outside the loop, to select a dummy "select all" list item. (I haven't tried this bit, so it might not work).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.