-
Notifications
You must be signed in to change notification settings - Fork 3
/
select2.sortable.js
96 lines (70 loc) · 2.19 KB
/
select2.sortable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
(function($) {
function getSortableUl($select) {
return $select.prev('.select2-container').find('ul.select2-choices');
};
function initSortableUl($ul, options) {
$ul.sortable({
forcePlaceholderSize: true,
items: 'li.select2-search-choice',
placeholder : '<li> </li>'
});
// Only bind event at initialization
if (options && options.bindSortEvent && options.$select) {
$ul.bind('sortupdate', function(e, ui) {
$($ul.find('li.select2-search-choice').get().reverse()).each(function() {
var id = $(this).data('select2Data').id,
$option = options.$select.find('option[value="' + id + '"]')[0];
options.$select.prepend($option);
});
});
}
};
function initSelect2Sortable($select) {
var observer,
$ul;
$select.select2();
$ul = getSortableUl($select);
observer = new MutationObserver(function(mutations) {
initSortableUl($ul);
observer.disconnect();
});
$select.on('select2-selecting', function() {
observer.observe($ul.get(0), { subtree: false, childList: true, attributes: false });
});
initSortableUl($ul, { bindSortEvent: true, $select: $select });
$select.data('hasSelect2Sortable', true);
};
function sortSelect2Sortable($select, val) {
var $ul = getSortableUl($select),
$lis = $ul.find('.select2-search-choice');
$.each(val, function(i, id) {
$lis.each(function() {
if (id == $(this).data('select2Data').id) {
$(this).insertBefore($ul.find('.select2-search-field'));
}
});
});
$ul.trigger('sortupdate');
}
$.fn.extend({
select2Sortable: function(val) {
this.each(function() {
var $select = $(this);
if (!$select.prop('multiple')) {
return;
}
if (!$select.data('hasSelect2Sortable')) {
initSelect2Sortable($select);
var values = $select.attr('data-order');
if (values) {
sortSelect2Sortable($select, values.split(','));
}
}
if (val) {
sortSelect2Sortable($select, val);
}
});
return this;
}
});
}(window.jQuery));