@kamranbaylarov/one-select 1.0.1 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -40
- package/js/one-select.js +33 -64
- package/js/one-select.min.js +7 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# 🎯 OneSelect - jQuery Multi-Select Dropdown Component
|
|
2
2
|
|
|
3
|
-
**Version:** 1.
|
|
3
|
+
**Version:** 1.1.1 | **Author:** Kamran Baylarov
|
|
4
4
|
|
|
5
5
|
A powerful, flexible, and feature-rich multi-select dropdown component for jQuery.
|
|
6
6
|
|
|
@@ -40,7 +40,8 @@ OneSelect is a powerful **jQuery-based** plugin that provides multi-select funct
|
|
|
40
40
|
- 🎪 **Multiple Instances** - Independent selects on same page
|
|
41
41
|
- 🌪 **Click Outside** - Close dropdown when clicking outside (default: true)
|
|
42
42
|
- 📍 **Smart Positioning** - Dropdown positioned with `position: fixed` using viewport coordinates
|
|
43
|
-
- 🔀 **Horizontal Scroll Detection** - Automatically closes on
|
|
43
|
+
- 🔀 **Horizontal Scroll Detection** - Automatically closes on horizontal scroll (Apple devices: 100px threshold, others: immediate)
|
|
44
|
+
- 🍎 **Cross-Platform** - Smart device detection for Apple touchpad/mouse compatibility
|
|
44
45
|
|
|
45
46
|
---
|
|
46
47
|
|
|
@@ -140,11 +141,8 @@ $('#mySelect').oneSelect({
|
|
|
140
141
|
| `selectAllText` | String | `'Select All'` | "Select All" button text |
|
|
141
142
|
| `okText` | String | `'OK'` | OK button text |
|
|
142
143
|
| `cancelText` | String | `'Cancel'` | Cancel button text |
|
|
143
|
-
| `data` | Array | `[]` | Options list (string
|
|
144
|
-
| `
|
|
145
|
-
| `value` | String/Array/null | `null` | Single or array value - pre-selects items |
|
|
146
|
-
| `valueField` | String | `'value'` | Value field name in object array |
|
|
147
|
-
| `labelField` | String | `'label'` | Label field name in object array |
|
|
144
|
+
| `data` | Array | `[]` | Options list (string array only) |
|
|
145
|
+
| `value` | Number/Array/null | `null` | Single index or array of indices to pre-select |
|
|
148
146
|
| `showCheckbox` | Boolean | `true` | Show/hide checkboxes |
|
|
149
147
|
| `showBadges` | Boolean | `false` | Show badges in trigger |
|
|
150
148
|
| `showBadgesExternal` | String/null | `null` | External element ID (for badges) |
|
|
@@ -152,7 +150,7 @@ $('#mySelect').oneSelect({
|
|
|
152
150
|
| `searchPlaceholder` | String | `'Search...'` | Search input placeholder text |
|
|
153
151
|
| `searchUrl` | String/null | `null` | URL for AJAX search (GET request with `q` parameter) |
|
|
154
152
|
| `searchDebounceDelay` | Number | `300` | Delay in milliseconds for search debounce |
|
|
155
|
-
| `closeOnScroll` | Boolean | `false` | Close dropdown on page scroll |
|
|
153
|
+
| `closeOnScroll` | Boolean | `false` | Close dropdown on **vertical** page scroll (horizontal scroll has independent behavior) |
|
|
156
154
|
| `closeOnOutside` | Boolean | `true` | Close dropdown when clicking outside |
|
|
157
155
|
| `submitForm` | Boolean | `false` | Submit form on OK click |
|
|
158
156
|
| `submitOnOutside` | Boolean | `false` | Submit form on outside click |
|
|
@@ -182,10 +180,7 @@ All parameters can be set via HTML data attributes. Data attributes **override J
|
|
|
182
180
|
| `data-ones-ok-text` | `okText` | String | `data-ones-ok-text="Confirm"` |
|
|
183
181
|
| `data-ones-cancel-text` | `cancelText` | String | `data-ones-cancel-text="Cancel"` |
|
|
184
182
|
| `data-ones-data` | `data` | Array | `data-ones-data='["A","B","C"]'` |
|
|
185
|
-
| `data-ones-
|
|
186
|
-
| `data-ones-value` | `value` | String/Array | `data-ones-value='"A"'` or `data-ones-value='["A","C"]'` |
|
|
187
|
-
| `data-ones-value-field` | `valueField` | String | `data-ones-value-field="id"` |
|
|
188
|
-
| `data-ones-label-field` | `labelField` | String | `data-ones-label-field="name"` |
|
|
183
|
+
| `data-ones-value` | `value` | Number/Array | `data-ones-value='"0"'` or `data-ones-value='["0","2"]'` |
|
|
189
184
|
| `data-ones-name` | `name` | String | `data-ones-name="items"` |
|
|
190
185
|
| `data-ones-multiple` | `multiple` | Boolean | `data-ones-multiple="true"` |
|
|
191
186
|
| `data-ones-show-checkbox` | `showCheckbox` | Boolean | `data-ones-show-checkbox="false"` |
|
|
@@ -342,45 +337,70 @@ $('#mySelect').oneSelect({
|
|
|
342
337
|
});
|
|
343
338
|
```
|
|
344
339
|
|
|
345
|
-
### 2.
|
|
340
|
+
### 2. How It Works
|
|
341
|
+
|
|
342
|
+
**Data Format:** String array only
|
|
343
|
+
|
|
344
|
+
```javascript
|
|
345
|
+
data: ['Apple', 'Banana', 'Cherry']
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
**Result:**
|
|
349
|
+
- **value** (what gets submitted): `0, 1, 2` (array indices)
|
|
350
|
+
- **label** (what user sees): `'Apple', 'Banana', 'Cherry'`
|
|
351
|
+
|
|
352
|
+
**Perfect for:**
|
|
353
|
+
- PHP associative arrays converted to indexed arrays
|
|
354
|
+
- Backend IDs as array indices
|
|
355
|
+
- Display values as array elements
|
|
356
|
+
|
|
357
|
+
**Example with PHP data:**
|
|
358
|
+
```php
|
|
359
|
+
// PHP
|
|
360
|
+
$items = [
|
|
361
|
+
5 => "M.Hadi_9_6/1",
|
|
362
|
+
6 => "Sarayevo_20_4/2/1",
|
|
363
|
+
7 => "Sarayevo_13B_3/2/1"
|
|
364
|
+
];
|
|
365
|
+
echo json_encode(array_values($items));
|
|
366
|
+
// Output: ["M.Hadi_9_6/1","Sarayevo_20_4/2/1","Sarayevo_13B_3/2/1"]
|
|
367
|
+
```
|
|
346
368
|
|
|
347
369
|
```javascript
|
|
370
|
+
// JavaScript
|
|
348
371
|
$('#mySelect').oneSelect({
|
|
349
|
-
data: [
|
|
350
|
-
{ id: 1, name: 'Apple', category: 'Fruit' },
|
|
351
|
-
{ id: 2, name: 'Banana', category: 'Fruit' }
|
|
352
|
-
],
|
|
353
|
-
valueField: 'id',
|
|
354
|
-
labelField: 'name'
|
|
372
|
+
data: ["M.Hadi_9_6/1", "Sarayevo_20_4/2/1", "Sarayevo_13B_3/2/1"]
|
|
355
373
|
});
|
|
374
|
+
// value: 0, 1, 2 (array indices)
|
|
375
|
+
// label: "M.Hadi_9_6/1", "Sarayevo_20_4/2/1", "Sarayevo_13B_3/2/1"
|
|
356
376
|
```
|
|
357
377
|
|
|
358
378
|
### 3. Value Parameter (Pre-selected Items)
|
|
359
379
|
|
|
360
380
|
```javascript
|
|
361
|
-
// Single value
|
|
381
|
+
// Single value (by index)
|
|
362
382
|
$('#mySelect').oneSelect({
|
|
363
383
|
data: ['Apple', 'Banana', 'Cherry', 'Mango'],
|
|
364
|
-
value:
|
|
384
|
+
value: 0 // Index 0 ('Apple') will be selected
|
|
365
385
|
});
|
|
366
386
|
|
|
367
387
|
// Array with multiple selection
|
|
368
388
|
$('#mySelect').oneSelect({
|
|
369
389
|
data: ['Apple', 'Banana', 'Cherry', 'Mango'],
|
|
370
|
-
value: ['Apple'
|
|
371
|
-
showBadges: true
|
|
390
|
+
value: [0, 2], // Indices 0 ('Apple') and 2 ('Cherry') will be selected
|
|
391
|
+
showBadges: true
|
|
372
392
|
});
|
|
373
393
|
|
|
374
394
|
// HTML data attribute
|
|
375
395
|
<div class="one-select"
|
|
376
396
|
data-ones-data='["Apple", "Banana", "Cherry"]'
|
|
377
|
-
data-ones-value='"
|
|
397
|
+
data-ones-value='"0"'> <!-- Single index -->
|
|
378
398
|
</div>
|
|
379
399
|
|
|
380
400
|
<!-- OR -->
|
|
381
401
|
<div class="one-select"
|
|
382
402
|
data-ones-data='["Apple", "Banana", "Cherry"]'
|
|
383
|
-
data-ones-value='["
|
|
403
|
+
data-ones-value='["0", "2"]'> <!-- Multiple indices -->
|
|
384
404
|
</div>
|
|
385
405
|
```
|
|
386
406
|
|
|
@@ -416,8 +436,8 @@ $('#mySelect').oneSelect({
|
|
|
416
436
|
|
|
417
437
|
Backend example:
|
|
418
438
|
```javascript
|
|
419
|
-
// Receive items array: [
|
|
420
|
-
//
|
|
439
|
+
// Receive items array: [0, 1] (indices of selected items)
|
|
440
|
+
// Use indices to get original values from your data array
|
|
421
441
|
```
|
|
422
442
|
|
|
423
443
|
### 6. AJAX Data Loading
|
|
@@ -774,11 +794,10 @@ $('#select1').oneSelect({
|
|
|
774
794
|
data: ['A', 'B', 'C']
|
|
775
795
|
});
|
|
776
796
|
|
|
777
|
-
// 2.
|
|
797
|
+
// 2. Pre-selected items (by index)
|
|
778
798
|
$('#select2').oneSelect({
|
|
779
|
-
data: [
|
|
780
|
-
|
|
781
|
-
labelField: 'title'
|
|
799
|
+
data: ['Apple', 'Banana', 'Cherry'],
|
|
800
|
+
value: [0, 2] // Selects indices 0 and 2
|
|
782
801
|
});
|
|
783
802
|
|
|
784
803
|
// 3. Badges
|
|
@@ -807,21 +826,15 @@ $('#select6').oneSelect({
|
|
|
807
826
|
closeOnOutside: true // Close when clicking outside (default)
|
|
808
827
|
});
|
|
809
828
|
|
|
810
|
-
// 7.
|
|
829
|
+
// 7. Search feature (local filtering)
|
|
811
830
|
$('#select7').oneSelect({
|
|
812
|
-
data: ['Apple', 'Banana', 'Cherry'],
|
|
813
|
-
value: ['Apple', 'Cherry'] // Pre-select these items
|
|
814
|
-
});
|
|
815
|
-
|
|
816
|
-
// 8. Search feature (local filtering)
|
|
817
|
-
$('#select8').oneSelect({
|
|
818
831
|
data: ['Apple', 'Banana', 'Cherry', 'Mango', 'Orange'],
|
|
819
832
|
showSearch: true,
|
|
820
833
|
searchPlaceholder: 'Search fruits...'
|
|
821
834
|
});
|
|
822
835
|
|
|
823
|
-
//
|
|
824
|
-
$('#
|
|
836
|
+
// 8. AJAX search with debounce
|
|
837
|
+
$('#select8').oneSelect({
|
|
825
838
|
showSearch: true,
|
|
826
839
|
searchUrl: '/api/search',
|
|
827
840
|
searchDebounceDelay: 500
|
package/js/one-select.js
CHANGED
|
@@ -87,10 +87,7 @@
|
|
|
87
87
|
okText: 'OK',
|
|
88
88
|
cancelText: 'Cancel',
|
|
89
89
|
data: [],
|
|
90
|
-
|
|
91
|
-
value: null, // Single value or array of values to pre-select
|
|
92
|
-
valueField: 'value',
|
|
93
|
-
labelField: 'label',
|
|
90
|
+
value: null, // Single value or array of values to pre-select (index-based)
|
|
94
91
|
showCheckbox: true,
|
|
95
92
|
showBadges: false,
|
|
96
93
|
showBadgesExternal: null,
|
|
@@ -133,10 +130,7 @@
|
|
|
133
130
|
'ones-ok-text': 'okText',
|
|
134
131
|
'ones-cancel-text': 'cancelText',
|
|
135
132
|
'ones-data': 'data',
|
|
136
|
-
'ones-selected': 'selectedValues',
|
|
137
133
|
'ones-value': 'value',
|
|
138
|
-
'ones-value-field': 'valueField',
|
|
139
|
-
'ones-label-field': 'labelField',
|
|
140
134
|
'ones-name': 'name',
|
|
141
135
|
'ones-multiple': 'multiple',
|
|
142
136
|
'ones-show-checkbox': 'showCheckbox',
|
|
@@ -161,7 +155,7 @@
|
|
|
161
155
|
return;
|
|
162
156
|
}
|
|
163
157
|
|
|
164
|
-
if (setting === 'data' || setting === '
|
|
158
|
+
if (setting === 'data' || setting === 'value') {
|
|
165
159
|
if (typeof value === 'string') {
|
|
166
160
|
try {
|
|
167
161
|
dataOptions[setting] = JSON.parse(value);
|
|
@@ -214,8 +208,14 @@
|
|
|
214
208
|
// Register instance in global registry
|
|
215
209
|
instances[this.instanceId] = this;
|
|
216
210
|
|
|
217
|
-
//
|
|
218
|
-
this.settings.
|
|
211
|
+
// Convert value to array if needed
|
|
212
|
+
if (this.settings.value !== null && this.settings.value !== undefined) {
|
|
213
|
+
if (!Array.isArray(this.settings.value)) {
|
|
214
|
+
this.settings.value = [this.settings.value];
|
|
215
|
+
}
|
|
216
|
+
} else {
|
|
217
|
+
this.settings.value = [];
|
|
218
|
+
}
|
|
219
219
|
|
|
220
220
|
this.wrapper = this.createWrapper();
|
|
221
221
|
this.trigger = this.createTrigger();
|
|
@@ -232,34 +232,6 @@
|
|
|
232
232
|
}
|
|
233
233
|
},
|
|
234
234
|
|
|
235
|
-
/**
|
|
236
|
-
* Merge value parameter into selectedValues array
|
|
237
|
-
* @param {*} value - Single value or array of values
|
|
238
|
-
* @param {Array} selectedValues - Existing selected values
|
|
239
|
-
* @returns {Array} Merged array of selected values
|
|
240
|
-
*/
|
|
241
|
-
mergeValueSettings: function(value, selectedValues) {
|
|
242
|
-
var result = selectedValues ? [].concat(selectedValues) : [];
|
|
243
|
-
|
|
244
|
-
if (value !== null && value !== undefined) {
|
|
245
|
-
if (Array.isArray(value)) {
|
|
246
|
-
// value is an array - merge all items
|
|
247
|
-
$.each(value, function(i, v) {
|
|
248
|
-
if ($.inArray(v, result) === -1) {
|
|
249
|
-
result.push(v);
|
|
250
|
-
}
|
|
251
|
-
});
|
|
252
|
-
} else {
|
|
253
|
-
// value is a single value - add if not already present
|
|
254
|
-
if ($.inArray(value, result) === -1) {
|
|
255
|
-
result.push(value);
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
return result;
|
|
261
|
-
},
|
|
262
|
-
|
|
263
235
|
build: function() {
|
|
264
236
|
// Add search input at the top of dropdown if enabled
|
|
265
237
|
if (this.settings.showSearch) {
|
|
@@ -362,17 +334,11 @@
|
|
|
362
334
|
|
|
363
335
|
var self = this;
|
|
364
336
|
$.each(this.settings.data, function(index, item) {
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
value = item[self.settings.valueField];
|
|
369
|
-
label = item[self.settings.labelField];
|
|
370
|
-
} else {
|
|
371
|
-
value = item;
|
|
372
|
-
label = item;
|
|
373
|
-
}
|
|
337
|
+
// Always: value = index, label = item
|
|
338
|
+
var value = index;
|
|
339
|
+
var label = item;
|
|
374
340
|
|
|
375
|
-
var isSelected = $.inArray(value, self.settings.
|
|
341
|
+
var isSelected = $.inArray(value, self.settings.value) !== -1;
|
|
376
342
|
var option = self.createOption(value, label, isSelected);
|
|
377
343
|
self.optionsContainer.append(option);
|
|
378
344
|
});
|
|
@@ -477,18 +443,11 @@
|
|
|
477
443
|
|
|
478
444
|
var self = this;
|
|
479
445
|
$.each(data, function(index, item) {
|
|
480
|
-
|
|
446
|
+
// Always: value = index, label = item
|
|
447
|
+
var value = index;
|
|
448
|
+
var label = item;
|
|
481
449
|
|
|
482
|
-
|
|
483
|
-
value = item[self.settings.valueField];
|
|
484
|
-
label = item[self.settings.labelField];
|
|
485
|
-
} else {
|
|
486
|
-
value = item;
|
|
487
|
-
label = item;
|
|
488
|
-
}
|
|
489
|
-
|
|
490
|
-
// Keep selection state if value was previously selected
|
|
491
|
-
var isSelected = $.inArray(value, self.settings.selectedValues) !== -1;
|
|
450
|
+
var isSelected = $.inArray(value, self.settings.value) !== -1;
|
|
492
451
|
var option = self.createOption(value, label, isSelected);
|
|
493
452
|
self.optionsContainer.append(option);
|
|
494
453
|
});
|
|
@@ -500,6 +459,15 @@
|
|
|
500
459
|
attachEvents: function() {
|
|
501
460
|
var self = this;
|
|
502
461
|
|
|
462
|
+
// Detect Apple device (macOS/iOS)
|
|
463
|
+
var isAppleDevice = navigator.platform.toUpperCase().indexOf('MAC') >= 0 ||
|
|
464
|
+
navigator.platform.toUpperCase().indexOf('IPHONE') >= 0 ||
|
|
465
|
+
navigator.platform.toUpperCase().indexOf('IPAD') >= 0 ||
|
|
466
|
+
navigator.userAgent.indexOf('Macintosh') !== -1;
|
|
467
|
+
|
|
468
|
+
// Set threshold based on device (100px for Apple, 0 for others)
|
|
469
|
+
var horizontalScrollThreshold = isAppleDevice ? 100 : 0;
|
|
470
|
+
|
|
503
471
|
this.trigger.on('click', function(e) {
|
|
504
472
|
e.stopPropagation();
|
|
505
473
|
self.toggle();
|
|
@@ -554,13 +522,14 @@
|
|
|
554
522
|
|
|
555
523
|
// Global horizontal scroll handler - close dropdown on any horizontal scroll
|
|
556
524
|
// Listen for wheel events with horizontal delta
|
|
525
|
+
// This is independent of closeOnScroll setting
|
|
557
526
|
$(document).on('wheel.onescroll', function(e) {
|
|
558
527
|
if (!self.wrapper.hasClass('open')) {
|
|
559
528
|
return;
|
|
560
529
|
}
|
|
561
530
|
|
|
562
|
-
// Check if horizontal scrolling (deltaX
|
|
563
|
-
if (e.originalEvent && Math.abs(e.originalEvent.deltaX) >
|
|
531
|
+
// Check if horizontal scrolling (deltaX > threshold)
|
|
532
|
+
if (e.originalEvent && Math.abs(e.originalEvent.deltaX) > horizontalScrollThreshold) {
|
|
564
533
|
self.close();
|
|
565
534
|
}
|
|
566
535
|
});
|
|
@@ -941,7 +910,7 @@
|
|
|
941
910
|
},
|
|
942
911
|
|
|
943
912
|
handleCancel: function() {
|
|
944
|
-
this.settings.
|
|
913
|
+
this.settings.value = [];
|
|
945
914
|
this.optionsContainer.find('input[type="checkbox"]').prop('checked', false);
|
|
946
915
|
this.optionsContainer.find('.cms-option').removeClass('selected');
|
|
947
916
|
this.updateSelectAllState();
|
|
@@ -960,7 +929,7 @@
|
|
|
960
929
|
},
|
|
961
930
|
|
|
962
931
|
setValue: function(values) {
|
|
963
|
-
this.settings.
|
|
932
|
+
this.settings.value = values || [];
|
|
964
933
|
this.renderOptions();
|
|
965
934
|
this.updateTriggerText();
|
|
966
935
|
this.updateHiddenInputs();
|
|
@@ -972,7 +941,7 @@
|
|
|
972
941
|
|
|
973
942
|
updateData: function(data) {
|
|
974
943
|
this.settings.data = data || [];
|
|
975
|
-
this.settings.
|
|
944
|
+
this.settings.value = [];
|
|
976
945
|
this.renderOptions();
|
|
977
946
|
this.updateTriggerText();
|
|
978
947
|
this.updateHiddenInputs();
|
package/js/one-select.min.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OneSelect - jQuery Multi-Select Dropdown Plugin
|
|
3
|
-
* Version: 1.
|
|
4
|
-
*
|
|
5
|
-
|
|
6
|
-
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&module.exports?module.exports=function(t,n){return void 0===n&&(n="undefined"!=typeof window?require("jquery"):require("jquery")(t)),e(n),n}:e(window.jQuery||window.$)}(function($){"use strict";var instances={},pluginName="oneSelect";function debounce(e,t){var n;return function(){var a=this,i=arguments;clearTimeout(n),n=setTimeout(function(){e.apply(a,i)},t)}}var OneSelect=function(e,t){this.element=e,this.$element=$(e),this.instanceId="ones-"+Math.random().toString(36).substr(2,9);var n=this.readDataAttributes();this.settings=$.extend({},OneSelect.defaults,t,n),this.init()};OneSelect.defaults={placeholder:"Select options...",selectAllText:"Select All",okText:"OK",cancelText:"Cancel",data:[],selectedValues:[],value:null,valueField:"value",labelField:"label",showCheckbox:!0,showBadges:!1,showBadgesExternal:null,showSearch:!1,searchPlaceholder:"Search...",searchUrl:null,searchDebounceDelay:300,closeOnScroll:!1,closeOnOutside:!0,submitForm:!1,submitOnOutside:!1,formId:null,name:null,multiple:!0,ajax:null,autoLoad:!0,beforeLoad:null,afterLoad:null,onLoadError:null,onChange:null,onSelect:null,onOk:null,onCancel:null},OneSelect.prototype={readDataAttributes:function(){var e=this,t={};const n={"ones-placeholder":"placeholder","ones-select-all-text":"selectAllText","ones-ok-text":"okText","ones-cancel-text":"cancelText","ones-data":"data","ones-selected":"selectedValues","ones-value":"value","ones-value-field":"valueField","ones-label-field":"labelField","ones-name":"name","ones-multiple":"multiple","ones-show-checkbox":"showCheckbox","ones-show-badges":"showBadges","ones-show-badges-external":"showBadgesExternal","ones-show-search":"showSearch","ones-search-placeholder":"searchPlaceholder","ones-search-url":"searchUrl","ones-search-debounce-delay":"searchDebounceDelay","ones-close-on-scroll":"closeOnScroll","ones-close-on-outside":"closeOnOutside","ones-submit-form":"submitForm","ones-submit-on-outside":"submitOnOutside","ones-form-id":"formId","ones-auto-load":"autoLoad"};return $.each(n,function(n,a){var i=e.$element.data(n);if(void 0!==i)switch(a){case"data":case"selectedValues":case"value":t[a]="string"==typeof i?function(){try{return JSON.parse(i)}catch(e){return console.warn("OneSelect: Invalid JSON for "+n,i),i}}():i;break;case"multiple":case"showCheckbox":case"showBadges":case"showSearch":case"closeOnScroll":case"closeOnOutside":case"submitForm":case"submitOnOutside":case"autoLoad":t[a]="string"==typeof i?"true"===i||"1"===i:!!i;break;case"searchDebounceDelay":t[a]="string"==typeof i?parseInt(i,10)||300:i||300;break;default:t[a]=i}}),function(){var e=this.$element.data("ones-ajax");if(e)try{"string"==typeof e&&(t.ajax=JSON.parse(e))}catch(e){console.warn("OneSelect: Invalid JSON for ones-ajax",e)}else t.ajax=e}.call(this),t},init:function(){instances[this.instanceId]=this,this.settings.selectedValues=this.mergeValueSettings(this.settings.value,this.settings.selectedValues),this.wrapper=this.createWrapper(),this.trigger=this.createTrigger(),this.dropdown=this.createDropdown(),this.searchInput=this.createSearchInput(),this.optionsContainer=this.createOptionsContainer(),this.buttons=this.createButtons(),this.build(),this.attachEvents(),this.settings.ajax&&this.settings.autoLoad&&this.loadData()},mergeValueSettings:function(e,t){var n=t?[].concat(t):[];return null!=e&&($.isArray(e)?$.each(e,function(e,t){-1===$.inArray(t,n)&&n.push(t)}):-1===$.inArray(e,n)&&n.push(e)),n},build:function(){this.settings.showSearch&&this.dropdown.append(this.searchInput),this.dropdown.append(this.optionsContainer),this.dropdown.append(this.buttons),this.wrapper.append(this.trigger),this.$element.append(this.wrapper),$("body").append(this.dropdown),this.renderOptions(),this.updateTriggerText(),this.updateHiddenInputs()},updateHiddenInputs:function(){if(this.settings.name){var e=null,t=this;e=this.settings.formId?$("#"+this.settings.formId):this.$element.closest("form");var n=e.length?e:this.wrapper;n.find('input.cms-hidden-input[data-cms-input="'+this.settings.name+'"]').remove();var a=this.settings.name;this.settings.multiple&&-1===a.indexOf("[")&&(a+="[]");var i=this.getSelectedValues();if(this.settings.multiple)$.each(i,function(e,n){var i=$('<input type="hidden" class="cms-hidden-input">').attr("name",a).attr("value",n).attr("data-cms-input",t.settings.name).attr("data-cms-value",n);n.append(i)}.bind({settings:this.settings,name:a}));else{var s=i.length>0?i.join(","):"",o=$('<input type="hidden" class="cms-hidden-input">').attr("name",a).attr("value",s).attr("data-cms-input",this.settings.name);n.append(o)}}},createWrapper:function(){return $('<div class="cms-wrapper"></div>')},createTrigger:function(){return $('<div class="cms-trigger"><span class="cms-selected-text cms-placeholder">'+this.settings.placeholder+"</span></div>")},createDropdown:function(){return $('<div class="cms-dropdown"></div>')},createSearchInput:function(){return $('<div class="cms-search-wrapper"><input type="text" class="cms-search-input" placeholder="'+this.settings.searchPlaceholder+'" /></div>')},createOptionsContainer:function(){return $('<div class="cms-options-container"></div>')},createButtons:function(){var e=$('<div class="cms-buttons"></div>');return this.okBtn=$('<button class="cms-btn cms-btn-ok">'+this.settings.okText+"</button>"),this.cancelBtn=$('<button class="cms-btn cms-btn-cancel">'+this.settings.cancelText+"</button>"),e.append(this.okBtn),e.append(this.cancelBtn),e},renderOptions:function(){this.optionsContainer.empty();var e=this.createOption("select-all",this.settings.selectAllText,!1);this.optionsContainer.append(e);var t=this;$.each(this.settings.data,function(e,n){var a,i;"object"==typeof n?(a=n[t.settings.valueField],i=n[t.settings.labelField]):a=i=n;var s=-1!==$.inArray(a,t.settings.selectedValues),o=t.createOption(a,i,s);t.optionsContainer.append(o)}),this.updateSelectAllState()},createOption:function(e,t,n){var a="cms-option";this.settings.showCheckbox||(a+=" cms-hide-checkbox"),n&&"select-all"!==e&&(a+=" selected");var i=$('<div class="'+a+'" data-value="'+e+'"></div>'),s=$('<input type="checkbox" value="'+e+'"'+(n?" checked":"")+">"),r=$("<label>"+t+"</label>");return i.append(s),i.append(r),i},filterOptions:function(e){var t=this.optionsContainer.find('.cms-option:not([data-value="select-all"])');""===e?t.show():t.each(function(){var t=$(this),n=t.find("label").text().toLowerCase();-1!==n.indexOf(e)?t.show():t.hide()})},performAjaxSearch:function(e){var t=this;this.optionsContainer.addClass("cms-loading"),$.ajax({url:this.settings.searchUrl,method:"GET",data:{q:e},dataType:"json",success:function(n){var a=n;"object"==typeof n&&n.data?a=n.data:"object"==typeof n&&n.results&&(a=n.results),t.updateSearchResults(a||[]),t.optionsContainer.removeClass("cms-loading")},error:function(n,a,i){console.error("OneSelect: Search error",i),t.optionsContainer.removeClass("cms-loading"),t.settings.onLoadError&&t.settings.onLoadError.call(t,n,a,i)}})},updateSearchResults:function(e){this.optionsContainer.find('.cms-option:not([data-value="select-all"])').remove();var t=this;$.each(e,function(e,n){var a,i;"object"==typeof n?(a=n[t.settings.valueField],i=n[t.settings.labelField]):a=i=n;var s=-1!==$.inArray(a,t.settings.selectedValues),o=t.createOption(a,i,s);t.optionsContainer.append(o)}),this.updateSelectAllState()},attachEvents:function(){var e=this;this.trigger.on("click",function(t){t.stopPropagation(),e.toggle()}),this.settings.showSearch&&(this.settings.searchUrl?function(){var t=debounce(function(t){e.performAjaxSearch(t)},e.settings.searchDebounceDelay);e.searchInput.find(".cms-search-input").on("keyup",function(){var e=$(this).val();e.length>0?t(e):function(){e.filterOptions("")}.call(e)})}():this.searchInput.find(".cms-search-input").on("keyup",function(){var t=$(this).val().toLowerCase();e.filterOptions(t)})),$(window).on("resize.cms",function(){e.wrapper.hasClass("open")&&e.updateDropdownPosition()}),this.settings.closeOnScroll?$(window).on("scroll.cms",function(){e.wrapper.hasClass("open")&&e.close()}):$(window).on("scroll.cms",function(){e.wrapper.hasClass("open")&&e.updateDropdownPosition()}),$(document).on("wheel.onescroll",function(t){!e.wrapper.hasClass("open")||t.originalEvent&&0===Math.abs(t.originalEvent.deltaX)||e.close()}),e._detectHorizontalScroll=function(){if(e.wrapper.hasClass("open")){if(window.scrollX!==e._lastWindowScrollX){if(e._lastWindowScrollX=window.scrollX,e._lastWindowScrollX>0)return void e.close()}for(var t=document.querySelectorAll("*"),n=0;n<t.length;n++){var a=t[n],i=function(e){return e===document?"document":e===document.documentElement?"html":e===document.body?"body":e.tagName+"-"+(e.id||e.className||Math.random().toString(36).substr(2,9))}(a);if(void 0!==e._elementScrollPositions[i]){var s=a.scrollLeft;if(s!==e._elementScrollPositions[i])return void e.close()}}}},e._elementScrollPositions={},e._lastWindowScrollX=window.scrollX;var t=e.open.bind(e);e.open=function(){e._elementScrollPositions={},e._lastWindowScrollX=window.scrollX;for(var n=document.querySelectorAll("*"),a=0;a<n.length;a++){var i=n[a];(i.scrollWidth>i.clientWidth||i.scrollHeight>i.clientHeight)&&(e._elementScrollPositions[function(e){return e===document?"document":e===document.documentElement?"html":e===document.body?"body":e.tagName+"-"+(e.id||e.className||Math.random().toString(36).substr(2,9))}(i)]=i.scrollLeft)}e._horizontalScrollInterval&&(clearInterval(e._horizontalScrollInterval),e._horizontalScrollInterval=null),e._horizontalScrollInterval=setInterval(function(){e._detectHorizontalScroll()},50),t()};var n=e.close.bind(e);e.close=function(){e._horizontalScrollInterval&&(clearInterval(e._horizontalScrollInterval),e._horizontalScrollInterval=null),e._elementScrollPositions={},n()},$(window).on("click.ones",function(t){if(e.settings.closeOnOutside&&e.wrapper.hasClass("open")){var n=$(t.target);if(0===n.closest(".cms-wrapper").length&&0===n.closest(".cms-dropdown").length){if(e.settings.submitOnOutside){e.updateTriggerText(),e.settings.onOk&&e.settings.onOk.call(e,e.getSelectedValues(),e.getSelectedLabels()),e.submitForm()}e.close()}}}),this.optionsContainer.on("click",".cms-option",function(t){t.stopPropagation();var n=$(this),a=n.find('input[type="checkbox"]');$(t.target).is('input[type="checkbox"]')||(a.prop("checked",!a.prop("checked")),e.handleOptionChange(n))}),this.optionsContainer.on("change",'input[type="checkbox"]',function(t){t.stopPropagation();var n=$(t.target).closest(".cms-option");e.handleOptionChange(n)}),this.okBtn.on("click",function(t){t.stopPropagation(),e.handleOk()}),this.cancelBtn.on("click",function(t){t.stopPropagation(),e.handleCancel()})},handleOptionChange:function(e){var t=e.data("value");if("select-all"===t){var n=e.find('input[type="checkbox"]');this.handleSelectAll(n.prop("checked"))}else{var a=e.find('input[type="checkbox"]');a.prop("checked")?e.addClass("selected"):e.removeClass("selected");var i=this;setTimeout(function(){i.updateSelectAllState(),i.updateTriggerText()},0)}this.updateHiddenInputs(),this.settings.onChange&&this.settings.onChange.call(this,this.getSelectedValues(),this.getSelectedLabels()),this.settings.onSelect&&this.settings.onSelect.call(this,this.getSelectedValues())},handleSelectAll:function(e){var t=this;this.optionsContainer.find('.cms-option:not([data-value="select-all"])').each(function(){var t=$(this);t.find('input[type="checkbox"]').prop("checked",e),e?t.addClass("selected"):t.removeClass("selected")}),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs()},updateSelectAllState:function(){var e=this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"]'),t=e.filter(":checked"),n=e.length,a=t.length,i=this.optionsContainer.find('.cms-option[data-value="select-all"] input[type="checkbox"]');i.prop("indeterminate",!1),i.prop("checked",!1),0===a?void 0:a===n&&n>0?i.prop("checked",!0):i.prop("indeterminate",!0)},getSelectedValues:function(){var e=[];return this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"]:checked').each(function(){var t=$(this).val();isNaN(t)&&""!==t||(t=Number(t)),e.push(t)}),e},getSelectedLabels:function(){var e=[];return this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"]:checked').siblings("label").each(function(){e.push($(this).text())}),e},updateTriggerText:function(){var e=this.getSelectedLabels(),t=this.getSelectedValues(),n=this.trigger.find(".cms-selected-text");0===e.length?n.empty().text(this.settings.placeholder).addClass("cms-placeholder"):this.settings.showBadges?(n.empty().removeClass("cms-placeholder"),$.each(t,function(t,a){var i=$('<span class="cms-badge"></span>'),s=$("<span></span>").text(e[t]),o=$('<button type="button" class="cms-badge-remove">×</button>');o.on("click",function(e){e.stopPropagation(),function(e){var t=this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"][value="'+e+'"]');t.length&&(t.prop("checked",!1),t.closest(".cms-option").removeClass("selected"),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs())}.call(this,a)}),i.append(s),i.append(o),n.append(i)}.bind(this))):(n.empty().removeClass("cms-placeholder"),n.text(e.length+" items selected")),this.updateExternalBadges(t,e)},updateExternalBadges:function(e,t){if(this.settings.showBadgesExternal){var n=$("#"+this.settings.showBadgesExternal);if(0!==n.length){if(n.empty(),0===e.length)return;$.each(e,function(e,a){var i=$('<span class="cms-badge"></span>'),s=$("<span></span>").text(t[e]),o=$('<button type="button" class="cms-badge-remove">×</button>');o.on("click",function(e){e.preventDefault(),e.stopPropagation(),function(e){var t=this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"][value="'+e+'"]');t.length&&(t.prop("checked",!1),t.closest(".cms-option").removeClass("selected"),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs())}.call(this,a)}),i.append(s),i.append(o),n.append(i)}.bind(this))}}},toggle:function(){this.wrapper.hasClass("open")?this.close():this.open()},open:function(){$(".cms-wrapper.open").not(this.wrapper).removeClass("open"),$(".cms-dropdown.open").not(this.dropdown).removeClass("open"),this.updateDropdownPosition(),this.wrapper.addClass("open"),this.dropdown.addClass("open")},updateDropdownPosition:function(){var e=this.wrapper[0].getBoundingClientRect(),t=this.wrapper.outerWidth();this.dropdown.css({position:"fixed",top:e.bottom+"px",left:e.left+"px",width:t+"px"})},close:function(){this.wrapper.removeClass("open"),this.dropdown.removeClass("open")},handleOk:function(){this.updateTriggerText();var e=this.getSelectedValues(),t=this.getSelectedLabels();this.settings.onOk&&this.settings.onOk.call(this,e,t),this.settings.submitForm&&this.submitForm(),this.close()},submitForm:function(){var e=this.settings.formId?$("#"+this.settings.formId):this.$element.closest("form");0===e.length?console.warn('OneSelect: Form with ID "'+this.settings.formId+'" not found'):0===e.length?console.warn("OneSelect: No parent form found"):e[0].submit()},handleCancel:function(){this.settings.selectedValues=[],this.optionsContainer.find('input[type="checkbox"]').prop("checked",!1),this.optionsContainer.find(".cms-option").removeClass("selected"),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs(),this.settings.onCancel&&this.settings.onCancel.call(this),this.settings.submitForm&&this.submitForm(),this.close()},setValue:function(e){this.settings.selectedValues=e||[],this.renderOptions(),this.updateTriggerText(),this.updateHiddenInputs()},getValue:function(){return this.getSelectedValues()},updateData:function(e){this.settings.data=e||[],this.settings.selectedValues=[],this.renderOptions(),this.updateTriggerText(),this.updateHiddenInputs()},loadData:function(e,t,n){var a=this,i=e||this.settings.ajax;if(i&&i.url){if(this.settings.beforeLoad&&this.settings.beforeLoad.call(this),this.trigger.find(".cms-selected-text").text("Loading..."),!i.url)return void console.error("OneSelect: Ajax configuration or url is missing");var s=$.extend(!0,{url:i.url,method:i.method||"GET",data:i.data||{},dataType:i.dataType||"json",success:function(e){var t=e;"object"==typeof e&&e.data?t=e.data:"object"==typeof e&&e.results&&(t=e.results),a.settings.data=t||[],a.renderOptions(),a.updateTriggerText(),a.settings.afterLoad&&a.settings.afterLoad.call(a,t,e),t&&t.call(a,t,e)},error:function(e,t,i){a.trigger.find(".cms-selected-text").text("Error loading data"),a.settings.onLoadError&&a.settings.onLoadError.call(a,e,t,i),n&&n.call(a,e,t,i)}},i);i.success&&(s.success=function(e,t){i.success(e),t(e)}),i.error&&(s.error=function(e,t,n){i.error(e,t,n),n(e,t,n)}),$.ajax(s)}else console.error("OneSelect: Ajax configuration or url is missing")},reload:function(){this.settings.ajax?this.loadData():console.warn("OneSelect: No ajax configuration found")},select:function(e){var t=this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"][value="'+e+'"]');t.length&&(t.prop("checked",!0),t.closest(".cms-option").addClass("selected"),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs())},unselect:function(e){var t=this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"][value="'+e+'"]');t.length&&(t.prop("checked",!1),t.closest(".cms-option").removeClass("selected"),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs())},selectAll:function(){this.handleSelectAll(!0)},unselectAll:function(){this.handleSelectAll(!1)},toggleSelection:function(e){var t=this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"][value="'+e+'"]');if(t.length){var n=t.prop("checked");t.prop("checked",!n);var a=t.closest(".cms-option");n?a.removeClass("selected"):a.addClass("selected"),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs()}},getInstanceId:function(){return this.instanceId},destroy:function(){delete instances[this.instanceId],$(window).off(".cms"),$(window).off(".ones"),$(document).off(".onescroll"),this.trigger.off(),this.okBtn.off(),this.cancelBtn.off(),this.optionsContainer.off(),this._horizontalScrollInterval&&(clearInterval(this._horizontalScrollInterval),this._horizontalScrollInterval=null),$('input.cms-hidden-input[data-cms-input="'+this.settings.name+'"]').remove(),this.wrapper.remove(),this.dropdown.remove(),this.$element.removeData(pluginName)}},OneSelect.getInstance=function(e){return instances[e]||null},OneSelect.getAllInstances=function(){return instances},$.fn[pluginName]=function(e){var t=arguments,n=this;return this.each(function(){var a=$(this),i=a.data(pluginName);i||"object"!=typeof e&&e||(i=new OneSelect(this,e),a.data(pluginName,i)),"string"==typeof e&&("value"===e?void 0!==t[1]?(i.setValue(t[1]),n=a):n=i.getValue():"getValues"===e?n=i.getSelectedValues():"getLabels"===e?n=i.getSelectedLabels():"getInstanceId"===e?n=i.getInstanceId():"updateData"===e?i.updateData(t[1]):"loadData"===e?i.loadData(t[1],t[2],t[3]):"reload"===e?i.reload():"select"===e?i.select(t[1]):"unselect"===e?i.unselect(t[1]):"selectAll"===e?i.selectAll():"unselectAll"===e?i.unselectAll():"toggleSelection"===e?i.toggleSelection(t[1]):"open"===e?i.open():"close"===e?i.close():"destroy"===e&&i.destroy())}),n},$.fn[pluginName].Constructor=OneSelect,$.fn[pluginName].getInstance=OneSelect.getInstance,$.fn[pluginName].getAllInstances=OneSelect.getAllInstances});
|
|
1
|
+
/**
|
|
2
|
+
* OneSelect - jQuery Multi-Select Dropdown Plugin
|
|
3
|
+
* Version: 1.2.0
|
|
4
|
+
* https://github.com/KamranBeylarov/one-select
|
|
5
|
+
* Licensed under MIT
|
|
6
|
+
*/
|
|
7
|
+
!function(e){"use strict";"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&module.exports?module.exports=function(t,n){return void 0===n&&(n="undefined"!=typeof window?require("jquery"):require("jquery")(t)),e(n),n}:e(window.jQuery||window.$)}(function(e){"use strict";var t={},n="oneSelect";function i(t,n){var i;return function(){var a=this,o=arguments;clearTimeout(i),i=setTimeout(function(){t.apply(a,o)},n)}}var a=function(e,n){this.element=e,this.$element=e(e),this.instanceId="ones-"+Math.random().toString(36).substr(2,9);var i=this.readDataAttributes();this.settings=e.extend({},o.defaults,n,i),this.init()};o.defaults={placeholder:"Select options...",selectAllText:"Select All",okText:"OK",cancelText:"Cancel",data:[],value:null,showCheckbox:!0,showBadges:!1,showBadgesExternal:null,showSearch:!1,searchPlaceholder:"Search...",searchUrl:null,searchDebounceDelay:300,closeOnScroll:!1,closeOnOutside:!0,submitForm:!1,submitOnOutside:!1,formId:null,name:null,multiple:!0,ajax:null,autoLoad:!0,beforeLoad:null,afterLoad:null,onLoadError:null,onChange:null,onSelect:null,onOk:null,onCancel:null},o.prototype={readDataAttributes:function(){var t=this,n={},i={"ones-placeholder":"placeholder","ones-select-all-text":"selectAllText","ones-ok-text":"okText","ones-cancel-text":"cancelText","ones-data":"data","ones-value":"value","ones-name":"name","ones-multiple":"multiple","ones-show-checkbox":"showCheckbox","ones-show-badges":"showBadges","ones-show-badges-external":"showBadgesExternal","ones-show-search":"showSearch","ones-search-placeholder":"searchPlaceholder","ones-search-url":"searchUrl","ones-search-debounce-delay":"searchDebounceDelay","ones-close-on-scroll":"closeOnScroll","ones-close-on-outside":"closeOnOutside","ones-submit-form":"submitForm","ones-submit-on-outside":"submitOnOutside","ones-form-id":"formId","ones-auto-load":"autoLoad"};return e.each(i,function(i,a){var o=t.$element.data(i);if(void 0!==o)if("data"===a||"value"===a)if("string"==typeof o)try{n[a]=JSON.parse(o)}catch(e){console.warn("OneSelect: Invalid JSON for "+i,o),n[a]=o}else n[a]=o;else if("multiple"===a||"showCheckbox"===a||"showBadges"===a||"showSearch"===a||"closeOnScroll"===a||"closeOnOutside"===a||"submitForm"===a||"submitOnOutside"===a||"autoLoad"===a)n[a]="string"==typeof o?"true"===o||"1"===o:!!o;else if("searchDebounceDelay"===a)n[a]="string"==typeof o?parseInt(o,10)||300:o||300;else n[a]=o});var a=this.$element.data("ones-ajax");if(a)"string"==typeof a?try{n.ajax=JSON.parse(a)}catch(e){console.warn("OneSelect: Invalid JSON for ones-ajax",a)}:n.ajax=a;return n},init:function(){t[this.instanceId]=this,null!==this.settings.value&&void 0!==this.settings.value?Array.isArray(this.settings.value)||(this.settings.value=[this.settings.value]):this.settings.value=[],this.wrapper=this.createWrapper(),this.trigger=this.createTrigger(),this.dropdown=this.createDropdown(),this.searchInput=this.createSearchInput(),this.optionsContainer=this.createOptionsContainer(),this.buttons=this.createButtons(),this.build(),this.attachEvents(),this.settings.ajax&&this.settings.autoLoad&&this.loadData()},build:function(){this.settings.showSearch&&this.dropdown.append(this.searchInput),this.dropdown.append(this.optionsContainer),this.dropdown.append(this.buttons),this.wrapper.append(this.trigger),this.$element.append(this.wrapper),e("body").append(this.dropdown),this.renderOptions(),this.updateTriggerText(),this.updateHiddenInputs()},updateHiddenInputs:function(){if(this.settings.name){var t=this.settings.formId?e("#"+this.settings.formId):this.$element.closest("form"),n=t.length?t:this.wrapper;n.find('input.cms-hidden-input[data-cms-input="'+this.settings.name+'"]').remove();var i=this.settings.name;this.settings.multiple&&-1===i.indexOf("[")&&(i+="[]");for(var a=this.getSelectedValues(),o=this,s=0;s<a.length;s++)n.append(e('<input type="hidden" class="cms-hidden-input">').attr("name",i).attr("value",a[s]).attr("data-cms-input",this.settings.name).attr("data-cms-value",a[s]))}},createWrapper:function(){return e('<div class="cms-wrapper"></div>')},createTrigger:function(){return e('<div class="cms-trigger"><span class="cms-selected-text cms-placeholder">'+this.settings.placeholder+"</span></div>")},createDropdown:function(){return e('<div class="cms-dropdown"></div>')},createSearchInput:function(){return e('<div class="cms-search-wrapper"><input type="text" class="cms-search-input" placeholder="'+this.settings.searchPlaceholder+'" /></div>')},createOptionsContainer:function(){return e('<div class="cms-options-container"></div>')},createButtons:function(){var t=e('<div class="cms-buttons"></div>');return this.okBtn=e('<button class="cms-btn cms-btn-ok">'+this.settings.okText+"</button>"),this.cancelBtn=e('<button class="cms-btn cms-btn-cancel">'+this.settings.cancelText+"</button>"),t.append(this.okBtn),t.append(this.cancelBtn),t},renderOptions:function(){this.optionsContainer.empty();var t=this.createOption("select-all",this.settings.selectAllText,!1);this.optionsContainer.append(t);var n=this;e.each(this.settings.data,function(e,t){var i=e,a=t,o=-1!==e.inArray(i,n.settings.value),s=n.createOption(i,a,o);n.optionsContainer.append(s)}),this.updateSelectAllState()},createOption:function(e,t,n){var i="cms-option";this.settings.showCheckbox||(i+=" cms-hide-checkbox"),n&&"select-all"!==e&&(i+=" selected");var a=e('<div class="'+i+'" data-value="'+e+'"></div>'),o=e('<input type="checkbox" value="'+e+'"'+(n?" checked":"")+">"),s=e("<label>"+t+"</label>");return a.append(o),a.append(s),a},filterOptions:function(t){var n=this.optionsContainer.find('.cms-option:not([data-value="select-all"])');""===t?n.show():n.each(function(){var n=e(this),i=n.find("label").text().toLowerCase();-1!==i.indexOf(t)?n.show():n.hide()})},performAjaxSearch:function(t){var n=this;this.optionsContainer.addClass("cms-loading"),e.ajax({url:this.settings.searchUrl,method:"GET",data:{q:t},dataType:"json",success:function(t){var i=t;"object"==typeof t&&t.data?i=t.data:"object"==typeof t&&t.results&&(i=t.results),n.updateSearchResults(i||[]),n.optionsContainer.removeClass("cms-loading")},error:function(e,t,i){console.error("OneSelect: Search error",i),n.optionsContainer.removeClass("cms-loading"),n.settings.onLoadError&&n.settings.onLoadError.call(n,e,t,i)}})},updateSearchResults:function(t){this.optionsContainer.find('.cms-option:not([data-value="select-all"])').remove();var n=this;e.each(t,function(e,t){var i=e,a=t,o=-1!==e.inArray(i,n.settings.value),s=n.createOption(i,a,o);n.optionsContainer.append(s)}),this.updateSelectAllState()},attachEvents:function(){var t=this,n=navigator.platform.toUpperCase().indexOf("MAC")>=0||navigator.platform.toUpperCase().indexOf("IPHONE")>=0||navigator.platform.toUpperCase().indexOf("IPAD")>=0||navigator.userAgent.indexOf("Macintosh")!==-1,a=n?100:0;this.trigger.on("click",function(e){e.stopPropagation(),t.toggle()}),this.settings.showSearch&&(this.settings.searchUrl?(e=".search-input",n=i(function(e){t.performAjaxSearch(e)},t.settings.searchDebounceDelay),t.searchInput.find(".cms-search-input").on("keyup",function(){var t=e(this).val();t.length>0?n(t):t.filterOptions("")})):t.searchInput.find(".cms-search-input").on("keyup",function(){var e=e(this).val().toLowerCase();t.filterOptions(e)})),e(window).on("resize.cms",function(){t.wrapper.hasClass("open")&&t.updateDropdownPosition()}),this.settings.closeOnScroll?e(window).on("scroll.cms",function(){t.wrapper.hasClass("open")&&t.close()}):e(window).on("scroll.cms",function(){t.wrapper.hasClass("open")&&t.updateDropdownPosition()}),e(document).on("wheel.onescroll",function(e){!t.wrapper.hasClass("open")||e.originalEvent&&Math.abs(e.originalEvent.deltaX)<=a||t.close()}),t._detectHorizontalScroll=function(){if(t.wrapper.hasClass("open")){if(window.scrollX!==t._lastWindowScrollX){if(t._lastWindowScrollX=window.scrollX,t._lastWindowScrollX>0)return void t.close()}for(var e=document.querySelectorAll("*"),n=0;n<e.length;n++){var i=e[n],o=function(e){return e===document?"document":e===document.documentElement?"html":e===document.body?"body":e.tagName+"-"+(e.id||e.className||Math.random().toString(36).substr(2,9))}(i);if(void 0!==t._elementScrollPositions[o]){var s=i.scrollLeft;if(s!==t._elementScrollPositions[o])return void t.close()}}}},t._elementScrollPositions={},t._lastWindowScrollX=window.scrollX,t._elementScrollPositions={},t._lastWindowScrollX=window.scrollX;for(var o=t.open.bind(t),s=t.close.bind(t),a=function(e){return e===document?"document":e===document.documentElement?"html":e===document.body?"body":e.tagName+"-"+(e.id||e.className||Math.random().toString(36).substr(2,9))},o=function(){t._elementScrollPositions={},t._lastWindowScrollX=window.scrollX;for(var e=document.querySelectorAll("*"),n=0;n<e.length;n++){var i=e[n];i.scrollWidth>i.clientWidth||i.scrollHeight>i.clientHeight?t._elementScrollPositions[a(i)]=i.scrollLeft:void 0}t._horizontalScrollInterval&&(clearInterval(t._horizontalScrollInterval),t._horizontalScrollInterval=null),t._horizontalScrollInterval=setInterval(function(){t._detectHorizontalScroll()},50),o()},t.close=function(){t._horizontalScrollInterval&&(clearInterval(t._horizontalScrollInterval),t._horizontalScrollInterval=null),t._elementScrollPositions={},s()},e(window).on("click.ones",function(e){if(t.settings.closeOnOutside&&t.wrapper.hasClass("open")){0===e(e.target).closest(".cms-wrapper").length&&0===e(e.target).closest(".cms-dropdown").length&&(t.settings.submitOnOutside&&(t.updateTriggerText(),t.settings.onOk&&t.settings.onOk.call(t,t.getSelectedValues(),t.getSelectedLabels()),t.submitForm()),t.close())}}),this.optionsContainer.on("click",".cms-option",function(e){e.stopPropagation();var n=e(this),i=n.find('input[type="checkbox"]');e(e.target).is('input[type="checkbox"]')||(i.prop("checked",!i.prop("checked")),t.handleOptionChange(n))}),this.optionsContainer.on("change",'input[type="checkbox"]',function(e){e.stopPropagation();var n=e(e.target).closest(".cms-option");t.handleOptionChange(n)}),this.okBtn.on("click",function(e){e.stopPropagation(),t.handleOk()}),this.cancelBtn.on("click",function(e){e.stopPropagation(),t.handleCancel()})},handleOptionChange:function(e){var t=e.data("value");if("select-all"===t){var n=e.find('input[type="checkbox"]');this.handleSelectAll(n.prop("checked"))}else{var i=e.find('input[type="checkbox"]');i.prop("checked")?e.addClass("selected"):e.removeClass("selected");var a=this;setTimeout(function(){a.updateSelectAllState(),a.updateTriggerText()},0)}this.updateHiddenInputs(),this.settings.onChange&&this.settings.onChange.call(this,this.getSelectedValues(),this.getSelectedLabels()),this.settings.onSelect&&this.settings.onSelect.call(this,this.getSelectedValues())},handleSelectAll:function(e){var t=this;this.optionsContainer.find('.cms-option:not([data-value="select-all"])').each(function(){var n=e(this);n.find('input[type="checkbox"]').prop("checked",e),e?n.addClass("selected"):n.removeClass("selected")}),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs()},updateSelectAllState:function(){var e=this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"]'),t=e.filter(":checked"),n=e.length,i=t.length,a=this.optionsContainer.find('.cms-option[data-value="select-all"] input[type="checkbox"]');a.prop("indeterminate",!1),a.prop("checked",!1),0===i||i===n&&n>0?a.prop("checked",!0):a.prop("indeterminate",!0)},getSelectedValues:function(){var t=[];return this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"]:checked').each(function(){var n=e(this).val();isNaN(n)&&""!==n||(n=Number(n)),t.push(n)}),t},getSelectedLabels:function(){var t=[];return this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"]:checked').siblings("label").each(function(){t.push(e(this).text())}),t},updateTriggerText:function(){var e=this.getSelectedLabels(),t=this.getSelectedValues(),n=this.trigger.find(".cms-selected-text");0===e.length?n.empty().text(this.settings.placeholder).addClass("cms-placeholder"):this.settings.showBadges?(n.empty().removeClass("cms-placeholder");var i=this;e.each(t,function(e,t){var a=i,o=e('<span class="cms-badge"></span>'),s=e("<span></span>").text(t[e]),r=e('<button type="button" class="cms-badge-remove">×</button>');r.on("click",function(e){e.stopPropagation(),i.unselect(t)}),o.append(s),o.append(r),n.append(o)})):n.empty().removeClass("cms-placeholder"),n.text(e.length+" items selected"),this.updateExternalBadges(t,e)},updateExternalBadges:function(t,n){if(this.settings.showBadgesExternal){var i=e("#"+this.settings.showBadgesExternal);if(0!==i.length){if(i.empty(),0===t.length)return;var a=this;e.each(t,function(e,t){var o=a,s=e('<span class="cms-badge"></span>'),r=e("<span></span>").text(n[e]),l=e('<button type="button" class="cms-badge-remove">×</button>');l.on("click",function(e){e.preventDefault(),e.stopPropagation(),a.unselect(t)}),s.append(r),s.append(l),i.append(s)})}}},toggle:function(){this.wrapper.hasClass("open")?this.close():this.open()},open:function(){e(".cms-wrapper.open").not(this.wrapper).removeClass("open"),e(".cms-dropdown.open").not(this.dropdown).removeClass("open"),this.updateDropdownPosition(),this.wrapper.addClass("open"),this.dropdown.addClass("open")},updateDropdownPosition:function(){var e=this.wrapper[0].getBoundingClientRect(),t=this.wrapper.outerWidth();this.dropdown.css({position:"fixed",top:e.bottom+"px",left:e.left+"px",width:t+"px"})},close:function(){this.wrapper.removeClass("open"),this.dropdown.removeClass("open")},handleOk:function(){this.updateTriggerText();var e=this.getSelectedValues(),t=this.getSelectedLabels();this.settings.onOk&&this.settings.onOk.call(this,e,t),this.settings.submitForm&&this.submitForm(),this.close()},submitForm:function(){var e=null;if(this.settings.formId?(e=e("#"+this.settings.formId),0===e.length&&console.warn('OneSelect: Form with ID "'+this.settings.formId+'" not found')):(e=this.$element.closest("form"),0===e.length&&console.warn("OneSelect: No parent form found")),0!==e.length&&e[0].submit()},handleCancel:function(){this.settings.value=[],this.optionsContainer.find('input[type="checkbox"]').prop("checked",!1),this.optionsContainer.find(".cms-option").removeClass("selected"),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs(),this.settings.onCancel&&this.settings.onCancel.call(this),this.settings.submitForm&&this.submitForm(),this.close()},setValue:function(e){this.settings.value=e||[],this.renderOptions(),this.updateTriggerText(),this.updateHiddenInputs()},getValue:function(){return this.getSelectedValues()},updateData:function(e){this.settings.data=e||[],this.settings.value=[],this.renderOptions(),this.updateTriggerText(),this.updateHiddenInputs()},loadData:function(t,n,i){var a=this,o=t||this.settings.ajax;if(o&&o.url){if(this.settings.beforeLoad&&this.settings.beforeLoad.call(this),this.trigger.find(".cms-selected-text").text("Loading..."),!o.url)return void console.error("OneSelect: Ajax configuration or url is missing");var s=e.extend(!0,{url:o.url,method:o.method||"GET",data:o.data||{},dataType:o.dataType||"json",success:function(e){var t=e;"object"==typeof e&&e.data?t=e.data:"object"==typeof e&&e.results&&(t=e.results),a.settings.data=t||[],a.renderOptions(),a.updateTriggerText(),a.settings.afterLoad&&a.settings.afterLoad.call(a,t,e),n&&n.call(a,t,e)},error:function(e,t,n){a.trigger.find(".cms-selected-text").text("Error loading data"),a.settings.onLoadError&&a.settings.onLoadError.call(a,e,t,n),i&&i.call(a,e,t,n)}},o);o.success&&(s.success=function(e){o.success(e),t(e)}),o.error&&(s.error=function(e,t,n){o.error(e,t,n),t(e,t,n)}),e.ajax(s)}else console.error("OneSelect: Ajax configuration or url is missing")},reload:function(){this.settings.ajax?this.loadData():console.warn("OneSelect: No ajax configuration found")},select:function(e){var t=this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"][value="'+e+'"]');t.length&&(t.prop("checked",!0),t.closest(".cms-option").addClass("selected"),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs())},unselect:function(e){var t=this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"][value="'+e+'"]');t.length&&(t.prop("checked",!1),t.closest(".cms-option").removeClass("selected"),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs())},selectAll:function(){this.handleSelectAll(!0)},unselectAll:function(){this.handleSelectAll(!1)},toggleSelection:function(e){var t=this.optionsContainer.find('.cms-option:not([data-value="select-all"]) input[type="checkbox"][value="'+e+'"]');if(t.length){var n=t.prop("checked");t.prop("checked",!n);var i=t.closest(".cms-option");n?i.removeClass("selected"):i.addClass("selected"),this.updateSelectAllState(),this.updateTriggerText(),this.updateHiddenInputs()}},getInstanceId:function(){return this.instanceId},destroy:function(){delete t[this.instanceId],e(window).off(".cms"),e(window).off(".ones"),e(document).off(".onescroll"),this.trigger.off(),this.okBtn.off(),this.cancelBtn.off(),this.optionsContainer.off(),this._horizontalScrollInterval&&(clearInterval(this._horizontalScrollInterval),this._horizontalScrollInterval=null),e('input.cms-hidden-input[data-cms-input="'+this.settings.name+'"]').remove(),this.wrapper.remove(),this.dropdown.remove(),this.$element.removeData(n)}},o.getInstance=function(e){return t[e]||null},o.getAllInstances=function(){return t},e.fn[n]=function(t){var i=arguments,a=this;return this.each(function(){var o=e(this),s=o.data(n);s||"object"!=typeof t&&t||(s=new o(this,t),o.data(n,s)),"string"==typeof t&&("value"===t?void 0!==i[1]?(s.setValue(i[1]),a=o):a=s.getValue():"getValues"===t?a=s.getSelectedValues():"getLabels"===t?a=s.getSelectedLabels():"getInstanceId"===t?a=s.getInstanceId():"updateData"===t?s.updateData(i[1]):"loadData"===t?s.loadData(i[1],i[2],i[3]):"reload"===t?s.reload():"select"===t?s.select(i[1]):"unselect"===t?s.unselect(i[1]):"selectAll"===t?s.selectAll():"unselectAll"===t?s.unselectAll():"toggleSelection"===t?s.toggleSelection(i[1]):"open"===t?s.open():"close"===t?s.close():"destroy"===t&&s.destroy())}),a},e.fn[n].Constructor=o,e.fn[n].getInstance=o.getInstance,e.fn[n].getAllInstances=o.getAllInstances});
|