-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathbootstrap-table-filter-control.js
744 lines (629 loc) · 27.9 KB
/
bootstrap-table-filter-control.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
/**
* @author: Dennis Hernández
* @webSite: http://djhvscf.github.io/Blog
* @version: v2.1.2
*/
(function ($) {
'use strict';
var sprintf = $.fn.bootstrapTable.utils.sprintf,
objectKeys = $.fn.bootstrapTable.utils.objectKeys;
var getOptionsFromSelectControl = function (selectControl) {
return selectControl.get(selectControl.length - 1).options;
};
var hideUnusedSelectOptions = function (selectControl, uniqueValues) {
var options = getOptionsFromSelectControl(selectControl);
for (var i = 0; i < options.length; i++) {
if (options[i].value !== "") {
if (!uniqueValues.hasOwnProperty(options[i].value)) {
selectControl.find(sprintf("option[value='%s']", options[i].value)).hide();
} else {
selectControl.find(sprintf("option[value='%s']", options[i].value)).show();
}
}
}
};
var addOptionToSelectControl = function (selectControl, value, text) {
value = $.trim(value);
selectControl = $(selectControl.get(selectControl.length - 1));
if (!existOptionInSelectControl(selectControl, value)) {
selectControl.append($("<option></option>")
.attr("value", value)
.text($('<div />').html(text).text()));
}
};
var sortSelectControl = function (selectControl) {
selectControl = $(selectControl.get(selectControl.length - 1));
var $opts = selectControl.find('option:gt(0)');
$opts.sort(function (a, b) {
a = $(a).text().toLowerCase();
b = $(b).text().toLowerCase();
if ($.isNumeric(a) && $.isNumeric(b)) {
// Convert numerical values from string to float.
a = parseFloat(a);
b = parseFloat(b);
}
return a > b ? 1 : a < b ? -1 : 0;
});
selectControl.find('option:gt(0)').remove();
selectControl.append($opts);
};
var existOptionInSelectControl = function (selectControl, value) {
var options = getOptionsFromSelectControl(selectControl);
for (var i = 0; i < options.length; i++) {
if (options[i].value === value.toString()) {
//The value is not valid to add
return true;
}
}
//If we get here, the value is valid to add
return false;
};
var fixHeaderCSS = function (that) {
that.$tableHeader.css('height', '77px');
};
var getCurrentHeader = function (that) {
var header = that.$header;
if (that.options.height) {
header = that.$tableHeader;
}
return header;
};
var getCurrentSearchControls = function (that) {
var searchControls = 'select, input';
if (that.options.height) {
searchControls = 'table select, table input';
}
return searchControls;
};
var getCursorPosition = function(el) {
if ($.fn.bootstrapTable.utils.isIEBrowser()) {
if ($(el).is('input[type=text]')) {
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
} else {
return -1;
}
} else {
return -1;
}
};
var setCursorPosition = function (el) {
$(el).val(el.value);
};
var copyValues = function (that) {
var header = getCurrentHeader(that),
searchControls = getCurrentSearchControls(that);
that.options.valuesFilterControl = [];
header.find(searchControls).each(function () {
that.options.valuesFilterControl.push(
{
field: $(this).closest('[data-field]').data('field'),
value: $(this).val(),
position: getCursorPosition($(this).get(0))
});
});
};
var setValues = function(that) {
var field = null,
result = [],
header = getCurrentHeader(that),
searchControls = getCurrentSearchControls(that);
if (that.options.valuesFilterControl.length > 0) {
header.find(searchControls).each(function (index, ele) {
field = $(this).closest('[data-field]').data('field');
result = $.grep(that.options.valuesFilterControl, function (valueObj) {
return valueObj.field === field;
});
if (result.length > 0) {
$(this).val(result[0].value);
setCursorPosition($(this).get(0), result[0].position);
}
});
}
};
var collectBootstrapCookies = function cookiesRegex() {
var cookies = [],
foundCookies = document.cookie.match(/(?:bs.table.)(\w*)/g);
if (foundCookies) {
$.each(foundCookies, function (i, cookie) {
if (/./.test(cookie)) {
cookie = cookie.split(".").pop();
}
if ($.inArray(cookie, cookies) === -1) {
cookies.push(cookie);
}
});
return cookies;
}
};
var initFilterSelectControls = function (that) {
var data = that.data,
itemsPerPage = that.pageTo < that.options.data.length ? that.options.data.length : that.pageTo,
isColumnSearchableViaSelect = function (column) {
return column.filterControl && column.filterControl.toLowerCase() === 'select' && column.searchable;
},
isFilterDataNotGiven = function (column) {
return column.filterData === undefined || column.filterData.toLowerCase() === 'column';
},
hasSelectControlElement = function (selectControl) {
return selectControl && selectControl.length > 0;
};
var z = that.options.pagination ?
(that.options.sidePagination === 'server' ? that.pageTo : that.options.totalRows) :
that.pageTo;
$.each(that.header.fields, function (j, field) {
var column = that.columns[that.fieldsColumnsIndex[field]],
selectControl = $('.bootstrap-table-filter-control-' + escapeID(column.field));
if (isColumnSearchableViaSelect(column) && isFilterDataNotGiven(column) && hasSelectControlElement(selectControl)) {
if (selectControl.get(selectControl.length - 1).options.length === 0) {
//Added the default option
addOptionToSelectControl(selectControl, '', '');
}
var uniqueValues = {};
for (var i = 0; i < z; i++) {
//Added a new value
var fieldValue = data[i][field],
formattedValue = $.fn.bootstrapTable.utils.calculateObjectValue(that.header, that.header.formatters[j], [fieldValue, data[i], i], fieldValue);
uniqueValues[formattedValue] = fieldValue;
}
for (var key in uniqueValues) {
addOptionToSelectControl(selectControl, uniqueValues[key], key);
}
sortSelectControl(selectControl);
if (that.options.hideUnusedSelectOptions) {
hideUnusedSelectOptions(selectControl, uniqueValues);
}
}
});
};
var escapeID = function(id) {
return String(id).replace( /(:|\.|\[|\]|,)/g, "\\$1" );
};
var createControls = function (that, header) {
var addedFilterControl = false,
isVisible,
html;
$.each(that.columns, function (i, column) {
isVisible = 'hidden';
html = [];
if (!column.visible) {
return;
}
if (!column.filterControl) {
html.push('<div class="no-filter-control"></div>');
} else {
html.push('<div class="filter-control">');
var nameControl = column.filterControl.toLowerCase();
if (column.searchable && that.options.filterTemplate[nameControl]) {
addedFilterControl = true;
isVisible = 'visible';
html.push(that.options.filterTemplate[nameControl](that, column.field, isVisible, column.filterControlPlaceholder ? column.filterControlPlaceholder : "", "filter-control-" + i));
}
}
$.each(header.children().children(), function (i, tr) {
tr = $(tr);
if (tr.data('field') === column.field) {
tr.find('.fht-cell').append(html.join(''));
return false;
}
});
if (column.filterData !== undefined && column.filterData.toLowerCase() !== 'column') {
var filterDataType = getFilterDataMethod(filterDataMethods, column.filterData.substring(0, column.filterData.indexOf(':')));
var filterDataSource, selectControl;
if (filterDataType !== null) {
filterDataSource = column.filterData.substring(column.filterData.indexOf(':') + 1, column.filterData.length);
selectControl = $('.bootstrap-table-filter-control-' + escapeID(column.field));
addOptionToSelectControl(selectControl, '', '');
filterDataType(filterDataSource, selectControl);
} else {
throw new SyntaxError('Error. You should use any of these allowed filter data methods: var, json, url.' + ' Use like this: var: {key: "value"}');
}
var variableValues, key;
switch (filterDataType) {
case 'url':
$.ajax({
url: filterDataSource,
dataType: 'json',
success: function (data) {
for (var key in data) {
addOptionToSelectControl(selectControl, key, data[key]);
}
sortSelectControl(selectControl);
}
});
break;
case 'var':
variableValues = window[filterDataSource];
for (key in variableValues) {
addOptionToSelectControl(selectControl, key, variableValues[key]);
}
sortSelectControl(selectControl);
break;
case 'jso':
variableValues = JSON.parse(filterDataSource);
for (key in variableValues) {
addOptionToSelectControl(selectControl, key, variableValues[key]);
}
sortSelectControl(selectControl);
break;
}
}
});
if (addedFilterControl) {
header.off('keyup', 'input').on('keyup', 'input', function (event) {
if (that.options.searchOnEnterKey && event.keyCode !== 13) {
return;
}
if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
return;
}
clearTimeout(event.currentTarget.timeoutId || 0);
event.currentTarget.timeoutId = setTimeout(function () {
that.onColumnSearch(event);
}, that.options.searchTimeOut);
});
header.off('change', 'select').on('change', 'select', function (event) {
if (that.options.searchOnEnterKey && event.keyCode !== 13) {
return;
}
if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
return;
}
clearTimeout(event.currentTarget.timeoutId || 0);
event.currentTarget.timeoutId = setTimeout(function () {
that.onColumnSearch(event);
}, that.options.searchTimeOut);
});
header.off('mouseup', 'input').on('mouseup', 'input', function (event) {
var $input = $(this),
oldValue = $input.val();
if (oldValue === "") {
return;
}
setTimeout(function(){
var newValue = $input.val();
if (newValue === "") {
clearTimeout(event.currentTarget.timeoutId || 0);
event.currentTarget.timeoutId = setTimeout(function () {
that.onColumnSearch(event);
}, that.options.searchTimeOut);
}
}, 1);
});
if (header.find('.date-filter-control').length > 0) {
$.each(that.columns, function (i, column) {
if (column.filterControl !== undefined && column.filterControl.toLowerCase() === 'datepicker') {
header.find('.date-filter-control.bootstrap-table-filter-control-' + column.field).datepicker(column.filterDatepickerOptions)
.on('changeDate', function (e) {
$(sprintf("#%s", e.currentTarget.id)).val(e.currentTarget.value);
//Fired the keyup event
$(e.currentTarget).keyup();
});
}
});
}
} else {
header.find('.filterControl').hide();
}
};
var getDirectionOfSelectOptions = function (alignment) {
alignment = alignment === undefined ? 'left' : alignment.toLowerCase();
switch (alignment) {
case 'left':
return 'ltr';
case 'right':
return 'rtl';
case 'auto':
return 'auto';
default:
return 'ltr';
}
};
var filterDataMethods =
{
'var': function (filterDataSource, selectControl) {
var variableValues = window[filterDataSource];
for (var key in variableValues) {
addOptionToSelectControl(selectControl, key, variableValues[key]);
}
sortSelectControl(selectControl);
},
'url': function (filterDataSource, selectControl) {
$.ajax({
url: filterDataSource,
dataType: 'json',
success: function (data) {
for (var key in data) {
addOptionToSelectControl(selectControl, key, data[key]);
}
sortSelectControl(selectControl);
}
});
},
'json':function (filterDataSource, selectControl) {
var variableValues = JSON.parse(filterDataSource);
for (var key in variableValues) {
addOptionToSelectControl(selectControl, key, variableValues[key]);
}
sortSelectControl(selectControl);
}
};
var getFilterDataMethod = function (objFilterDataMethod, searchTerm) {
var keys = Object.keys(objFilterDataMethod);
for (var i = 0; i < keys.length; i++) {
if (keys[i] === searchTerm) {
return objFilterDataMethod[searchTerm];
}
}
return null;
};
$.extend($.fn.bootstrapTable.defaults, {
filterControl: false,
onColumnSearch: function (field, text) {
return false;
},
filterShowClear: false,
alignmentSelectControlOptions: undefined,
filterTemplate: {
input: function (that, field, isVisible, placeholder) {
return sprintf('<input type="text" class="form-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s" placeholder="%s">', field, isVisible, placeholder);
},
select: function (that, field, isVisible) {
return sprintf('<select class="form-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s" dir="%s"></select>',
field, isVisible, getDirectionOfSelectOptions(that.options.alignmentSelectControlOptions));
},
datepicker: function (that, field, isVisible) {
return sprintf('<input type="text" class="form-control date-filter-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s">', field, isVisible);
}
},
disableControlWhenSearch: false,
searchOnEnterKey: false,
//internal variables
valuesFilterControl: []
});
$.extend($.fn.bootstrapTable.columnDefaults, {
filterControl: undefined,
filterData: undefined,
filterDatepickerOptions: undefined,
filterStrictSearch: false,
filterStartsWithSearch: false,
filterControlPlaceholder: ""
});
$.extend($.fn.bootstrapTable.Constructor.EVENTS, {
'column-search.bs.table': 'onColumnSearch'
});
$.extend($.fn.bootstrapTable.defaults.icons, {
clear: 'glyphicon-trash icon-clear'
});
$.extend($.fn.bootstrapTable.locales, {
formatClearFilters: function () {
return 'Clear Filters';
}
});
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
$.fn.bootstrapTable.methods.push('triggerSearch');
var BootstrapTable = $.fn.bootstrapTable.Constructor,
_init = BootstrapTable.prototype.init,
_initToolbar = BootstrapTable.prototype.initToolbar,
_initHeader = BootstrapTable.prototype.initHeader,
_initBody = BootstrapTable.prototype.initBody,
_initSearch = BootstrapTable.prototype.initSearch;
BootstrapTable.prototype.init = function () {
//Make sure that the filterControl option is set
if (this.options.filterControl) {
var that = this;
// Compatibility: IE < 9 and old browsers
if (!Object.keys) {
objectKeys();
}
//Make sure that the internal variables are set correctly
this.options.valuesFilterControl = [];
this.$el.on('reset-view.bs.table', function () {
//Create controls on $tableHeader if the height is set
if (!that.options.height) {
return;
}
//Avoid recreate the controls
if (that.$tableHeader.find('select').length > 0 || that.$tableHeader.find('input').length > 0) {
return;
}
createControls(that, that.$tableHeader);
}).on('post-header.bs.table', function () {
setValues(that);
}).on('post-body.bs.table', function () {
if (that.options.height) {
fixHeaderCSS(that);
}
}).on('column-switch.bs.table', function() {
setValues(that);
}).on('load-success.bs.table', function() {
that.EnableControls(true);
}).on('load-error.bs.table', function() {
that.EnableControls(true);
});
}
_init.apply(this, Array.prototype.slice.apply(arguments));
};
BootstrapTable.prototype.initToolbar = function () {
this.showToolbar = this.showToolbar || this.options.filterControl && this.options.filterShowClear;
_initToolbar.apply(this, Array.prototype.slice.apply(arguments));
if (this.options.filterControl && this.options.filterShowClear) {
var $btnGroup = this.$toolbar.find('>.btn-group'),
$btnClear = $btnGroup.find('.filter-show-clear');
if (!$btnClear.length) {
$btnClear = $([
sprintf('<button class="btn btn-%s filter-show-clear" ', this.options.buttonsClass),
sprintf('type="button" title="%s">', this.options.formatClearFilters()),
sprintf('<i class="%s %s"></i> ', this.options.iconsPrefix, this.options.icons.clear),
'</button>'
].join('')).appendTo($btnGroup);
$btnClear.off('click').on('click', $.proxy(this.clearFilterControl, this));
}
}
};
BootstrapTable.prototype.initHeader = function () {
_initHeader.apply(this, Array.prototype.slice.apply(arguments));
if (!this.options.filterControl) {
return;
}
createControls(this, this.$header);
};
BootstrapTable.prototype.initBody = function () {
_initBody.apply(this, Array.prototype.slice.apply(arguments));
initFilterSelectControls(this);
};
BootstrapTable.prototype.initSearch = function () {
_initSearch.apply(this, Array.prototype.slice.apply(arguments));
if (this.options.sidePagination === 'server') {
return;
}
var that = this;
var fp = $.isEmptyObject(that.filterColumnsPartial) ? null : that.filterColumnsPartial;
//Check partial column filter
that.data = fp ? $.grep(that.data, function (item, i) {
for (var key in fp) {
var thisColumn = that.columns[that.fieldsColumnsIndex[key]];
var fval = fp[key].toLowerCase();
var value = item[key];
// Fix #142: search use formated data
if (thisColumn && thisColumn.searchFormatter) {
value = $.fn.bootstrapTable.utils.calculateObjectValue(that.header,
that.header.formatters[$.inArray(key, that.header.fields)],
[value, item, i], value);
}
if($.inArray(key, that.header.fields) !== -1 ) {
if(typeof value === 'string' || typeof value === 'number') {
if (thisColumn.filterStrictSearch) {
if(value.toString().toLowerCase() === fval.toString().toLowerCase()) {
return true;
}
} else if (thisColumn.filterStartsWithSearch) {
if((value + '').toLowerCase().indexOf(fval) === 0) {
return true;
}
} else {
if((value + '').toLowerCase().indexOf(fval) !== -1) {
return true;
}
}
}
}
}
return false;
}) : that.data;
};
BootstrapTable.prototype.initColumnSearch = function(filterColumnsDefaults) {
copyValues(this);
if (filterColumnsDefaults) {
this.filterColumnsPartial = filterColumnsDefaults;
this.updatePagination();
for (var filter in filterColumnsDefaults) {
this.trigger('column-search', filter, filterColumnsDefaults[filter]);
}
}
};
BootstrapTable.prototype.onColumnSearch = function (event) {
if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
return;
}
copyValues(this);
var text = $.trim($(event.currentTarget).val());
var $field = $(event.currentTarget).closest('[data-field]').data('field');
if ($.isEmptyObject(this.filterColumnsPartial)) {
this.filterColumnsPartial = {};
}
if (text) {
this.filterColumnsPartial[$field] = text;
} else {
delete this.filterColumnsPartial[$field];
}
// if the searchText is the same as the previously selected column value,
// bootstrapTable will not try searching again (even though the selected column
// may be different from the previous search). As a work around
// we're manually appending some text to bootrap's searchText field
// to guarantee that it will perform a search again when we call this.onSearch(event)
this.searchText += "randomText";
this.options.pageNumber = 1;
this.EnableControls(false);
this.onSearch(event);
this.trigger('column-search', $field, text);
};
BootstrapTable.prototype.clearFilterControl = function () {
if (this.options.filterControl && this.options.filterShowClear) {
var that = this,
cookies = collectBootstrapCookies(),
header = getCurrentHeader(that),
table = header.closest('table'),
controls = header.find(getCurrentSearchControls(that)),
search = that.$toolbar.find('.search input'),
timeoutId = 0;
$.each(that.options.valuesFilterControl, function (i, item) {
item.value = '';
});
setValues(that);
// Clear each type of filter if it exists.
// Requires the body to reload each time a type of filter is found because we never know
// which ones are going to be present.
if (controls.length > 0) {
this.filterColumnsPartial = {};
$(controls[0]).trigger(controls[0].tagName === 'INPUT' ? 'keyup' : 'change');
} else {
return;
}
if (search.length > 0) {
that.resetSearch();
}
// use the default sort order if it exists. do nothing if it does not
if (that.options.sortName !== table.data('sortName') || that.options.sortOrder !== table.data('sortOrder')) {
var sorter = header.find(sprintf('[data-field="%s"]', $(controls[0]).closest('table').data('sortName')));
if (sorter.length > 0) {
that.onSort(table.data('sortName'), table.data('sortName'));
$(sorter).find('.sortable').trigger('click');
}
}
// clear cookies once the filters are clean
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
if (cookies && cookies.length > 0) {
$.each(cookies, function (i, item) {
if (that.deleteCookie !== undefined) {
that.deleteCookie(item);
}
});
}
}, that.options.searchTimeOut);
}
};
BootstrapTable.prototype.triggerSearch = function () {
var header = getCurrentHeader(this),
searchControls = getCurrentSearchControls(this);
header.find(searchControls).each(function () {
var el = $(this);
if(el.is('select')) {
el.change();
} else {
el.keyup();
}
});
};
BootstrapTable.prototype.EnableControls = function(enable) {
if((this.options.disableControlWhenSearch) && (this.options.sidePagination === 'server')) {
var header = getCurrentHeader(this),
searchControls = getCurrentSearchControls(this);
if(!enable) {
header.find(searchControls).prop('disabled', 'disabled');
} else {
header.find(searchControls).removeProp('disabled');
}
}
};
})(jQuery);