bootstrap-table-filter-control.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @version: v1.0.0
  5. */
  6. !function ($) {
  7. 'use strict';
  8. var sprintf = $.fn.bootstrapTable.utils.sprintf;
  9. var addOptionToSelectControl = function (selectControl, value, text) {
  10. value = $.trim(value);
  11. selectControl = $(selectControl.get(selectControl.length - 1));
  12. if (existOptionInSelectControl(selectControl, value)) {
  13. selectControl.append($("<option></option>")
  14. .attr("value", value)
  15. .text($('<div />').html(text).text()));
  16. // Sort it. Not overly efficient to do this here
  17. var $opts = selectControl.find('option:gt(0)');
  18. $opts.sort(function (a, b) {
  19. a = $(a).text().toLowerCase();
  20. b = $(b).text().toLowerCase();
  21. if ($.isNumeric(a) && $.isNumeric(b)) {
  22. // Convert numerical values from string to float.
  23. a = parseFloat(a);
  24. b = parseFloat(b);
  25. }
  26. return a > b ? 1 : a < b ? -1 : 0;
  27. });
  28. selectControl.find('option:gt(0)').remove();
  29. selectControl.append($opts);
  30. }
  31. };
  32. var existOptionInSelectControl = function (selectControl, value) {
  33. var options = selectControl.get(selectControl.length - 1).options;
  34. for (var i = 0; i < options.length; i++) {
  35. if (options[i].value === value.toString()) {
  36. //The value is not valid to add
  37. return false;
  38. }
  39. }
  40. //If we get here, the value is valid to add
  41. return true;
  42. };
  43. var fixHeaderCSS = function (that) {
  44. that.$tableHeader.css('height', '77px');
  45. };
  46. var getCurrentHeader = function (that) {
  47. var header = that.$header;
  48. if (that.options.height) {
  49. header = that.$tableHeader;
  50. }
  51. return header;
  52. };
  53. var getCurrentSearchControls = function (that) {
  54. var searchControls = 'select, input';
  55. if (that.options.height) {
  56. searchControls = 'table select, table input';
  57. }
  58. return searchControls;
  59. };
  60. var copyValues = function (that) {
  61. var header = getCurrentHeader(that),
  62. searchControls = getCurrentSearchControls(that);
  63. that.options.valuesFilterControl = [];
  64. header.find(searchControls).each(function () {
  65. that.options.valuesFilterControl.push(
  66. {
  67. field: $(this).closest('[data-field]').data('field'),
  68. value: $(this).val()
  69. });
  70. });
  71. };
  72. var setValues = function(that) {
  73. var field = null,
  74. result = [],
  75. header = getCurrentHeader(that),
  76. searchControls = getCurrentSearchControls(that);
  77. if (that.options.valuesFilterControl.length > 0) {
  78. header.find(searchControls).each(function (index, ele) {
  79. field = $(this).closest('[data-field]').data('field');
  80. result = $.grep(that.options.valuesFilterControl, function (valueObj) {
  81. return valueObj.field === field;
  82. });
  83. if (result.length > 0) {
  84. $(this).val(result[0].value);
  85. }
  86. });
  87. }
  88. };
  89. var collectBootstrapCookies = function cookiesRegex() {
  90. var cookies = [],
  91. foundCookies = document.cookie.match(/(?:bs.table.)(\w*)/g);
  92. if (foundCookies) {
  93. $.each(foundCookies, function (i, cookie) {
  94. if (/./.test(cookie)) {
  95. cookie = cookie.split(".").pop();
  96. }
  97. if ($.inArray(cookie, cookies) === -1) {
  98. cookies.push(cookie);
  99. }
  100. });
  101. return cookies;
  102. }
  103. };
  104. var createControls = function (that, header) {
  105. var addedFilterControl = false,
  106. isVisible,
  107. html,
  108. timeoutId = 0;
  109. $.each(that.columns, function (i, column) {
  110. isVisible = 'hidden';
  111. html = [];
  112. if (!column.visible) {
  113. return;
  114. }
  115. if (!column.filterControl) {
  116. html.push('<div style="height: 34px;"></div>');
  117. } else {
  118. html.push('<div style="margin: 0 2px 2px 2px;" class="filterControl">');
  119. var nameControl = column.filterControl.toLowerCase();
  120. if (column.searchable && that.options.filterTemplate[nameControl]) {
  121. addedFilterControl = true;
  122. isVisible = 'visible';
  123. html.push(that.options.filterTemplate[nameControl](that, column.field, isVisible));
  124. }
  125. }
  126. $.each(header.children().children(), function (i, tr) {
  127. tr = $(tr);
  128. if (tr.data('field') === column.field) {
  129. tr.find('.fht-cell').append(html.join(''));
  130. return false;
  131. }
  132. });
  133. if (column.filterData !== undefined && column.filterData.toLowerCase() !== 'column') {
  134. var filterDataType = column.filterData.substring(0, 3);
  135. var filterDataSource = column.filterData.substring(4, column.filterData.length);
  136. var selectControl = $('.' + column.field);
  137. addOptionToSelectControl(selectControl, '', '');
  138. switch (filterDataType) {
  139. case 'url':
  140. $.ajax({
  141. url: filterDataSource,
  142. dataType: 'json',
  143. success: function (data) {
  144. $.each(data, function (key, value) {
  145. addOptionToSelectControl(selectControl, key, value);
  146. });
  147. }
  148. });
  149. break;
  150. case 'var':
  151. var variableValues = window[filterDataSource];
  152. for (var key in variableValues) {
  153. addOptionToSelectControl(selectControl, key, variableValues[key]);
  154. }
  155. break;
  156. }
  157. }
  158. });
  159. if (addedFilterControl) {
  160. header.off('keyup', 'input').on('keyup', 'input', function (event) {
  161. clearTimeout(timeoutId);
  162. timeoutId = setTimeout(function () {
  163. that.onColumnSearch(event);
  164. }, that.options.searchTimeOut);
  165. });
  166. header.off('change', 'select').on('change', 'select', function (event) {
  167. clearTimeout(timeoutId);
  168. timeoutId = setTimeout(function () {
  169. that.onColumnSearch(event);
  170. }, that.options.searchTimeOut);
  171. });
  172. header.off('mouseup', 'input').on('mouseup', 'input', function (event) {
  173. var $input = $(this),
  174. oldValue = $input.val();
  175. if (oldValue === "") {
  176. return;
  177. }
  178. setTimeout(function(){
  179. var newValue = $input.val();
  180. if (newValue === "") {
  181. clearTimeout(timeoutId);
  182. timeoutId = setTimeout(function () {
  183. that.onColumnSearch(event);
  184. }, that.options.searchTimeOut);
  185. }
  186. }, 1);
  187. });
  188. if (header.find('.date-filter-control').length > 0) {
  189. $.each(that.columns, function (i, column) {
  190. if (column.filterControl !== undefined && column.filterControl.toLowerCase() === 'datepicker') {
  191. header.find('.date-filter-control.' + column.field).datepicker(column.filterDatepickerOptions)
  192. .on('changeDate', function (e) {
  193. //Fired the keyup event
  194. $(e.currentTarget).keyup();
  195. });
  196. }
  197. });
  198. }
  199. } else {
  200. header.find('.filterControl').hide();
  201. }
  202. };
  203. var getDirectionOfSelectOptions = function (alignment) {
  204. alignment = alignment === undefined ? 'left' : alignment.toLowerCase();
  205. switch (alignment) {
  206. case 'left':
  207. return 'ltr';
  208. case 'right':
  209. return 'rtl';
  210. case 'auto':
  211. return 'auto';
  212. default:
  213. return 'ltr'
  214. }
  215. };
  216. $.extend($.fn.bootstrapTable.defaults, {
  217. filterControl: false,
  218. onColumnSearch: function (field, text) {
  219. return false;
  220. },
  221. filterShowClear: false,
  222. alignmentSelectControlOptions: undefined,
  223. //internal variables
  224. valuesFilterControl: [],
  225. filterTemplate: {
  226. input: function (that, field, isVisible) {
  227. return sprintf('<input type="text" class="form-control %s" style="width: 100%; visibility: %s">', field, isVisible);
  228. },
  229. select: function (that, field, isVisible) {
  230. return sprintf('<select class="%s form-control" style="width: 100%; visibility: %s" dir="%s"></select>',
  231. field, isVisible, getDirectionOfSelectOptions(that.options.alignmentSelectControlOptions))
  232. },
  233. datepicker: function (that, field, isVisible) {
  234. return sprintf('<input type="text" class="date-filter-control %s form-control" style="width: 100%; visibility: %s">', field, isVisible);
  235. }
  236. }
  237. });
  238. $.extend($.fn.bootstrapTable.COLUMN_DEFAULTS, {
  239. filterControl: undefined,
  240. filterData: undefined,
  241. filterDatepickerOptions: undefined,
  242. filterStrictSearch: false
  243. });
  244. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  245. 'column-search.bs.table': 'onColumnSearch'
  246. });
  247. $.extend($.fn.bootstrapTable.defaults.icons, {
  248. clear: 'glyphicon-trash icon-clear'
  249. });
  250. var BootstrapTable = $.fn.bootstrapTable.Constructor,
  251. _init = BootstrapTable.prototype.init,
  252. _initToolbar = BootstrapTable.prototype.initToolbar,
  253. _initHeader = BootstrapTable.prototype.initHeader,
  254. _initBody = BootstrapTable.prototype.initBody,
  255. _initSearch = BootstrapTable.prototype.initSearch;
  256. BootstrapTable.prototype.init = function () {
  257. //Make sure that the filterControl option is set
  258. if (this.options.filterControl) {
  259. var that = this;
  260. //Make sure that the internal variables are set correctly
  261. this.options.valuesFilterControl = [];
  262. this.$el.on('reset-view.bs.table', function () {
  263. //Create controls on $tableHeader if the height is set
  264. if (!that.options.height) {
  265. return;
  266. }
  267. //Avoid recreate the controls
  268. if (that.$tableHeader.find('select').length > 0 || that.$tableHeader.find('input').length > 0) {
  269. return;
  270. }
  271. createControls(that, that.$tableHeader);
  272. }).on('post-header.bs.table', function () {
  273. setValues(that);
  274. }).on('post-body.bs.table', function () {
  275. if (that.options.height) {
  276. fixHeaderCSS(that);
  277. }
  278. }).on('column-switch.bs.table', function() {
  279. setValues(that);
  280. });
  281. }
  282. _init.apply(this, Array.prototype.slice.apply(arguments));
  283. };
  284. $.extend($.fn.bootstrapTable.locales, {
  285. formatClearFilters: function () {
  286. return 'Clear Filters';
  287. }
  288. });
  289. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales);
  290. BootstrapTable.prototype.initToolbar = function () {
  291. if ((!this.showToolbar) && (this.options.filterControl)) {
  292. this.showToolbar = this.options.filterControl;
  293. }
  294. _initToolbar.apply(this, Array.prototype.slice.apply(arguments));
  295. if (this.options.filterControl && this.options.filterShowClear) {
  296. var $btnGroup = this.$toolbar.find('>.btn-group'),
  297. $btnClear = $btnGroup.find('div.export');
  298. if (!$btnClear.length) {
  299. $btnClear = $([
  300. '<button class="btn btn-default" ',
  301. sprintf('type="button" title="%s">', this.options.formatClearFilters()),
  302. sprintf('<i class="%s %s"></i> ', this.options.iconsPrefix, this.options.icons.clear),
  303. '</button>',
  304. '</ul>'].join('')).appendTo($btnGroup);
  305. $btnClear.off('click').on('click', $.proxy(this.clearFilterControl, this));
  306. }
  307. }
  308. };
  309. BootstrapTable.prototype.initHeader = function () {
  310. _initHeader.apply(this, Array.prototype.slice.apply(arguments));
  311. if (!this.options.filterControl) {
  312. return;
  313. }
  314. createControls(this, this.$header);
  315. };
  316. BootstrapTable.prototype.initBody = function () {
  317. _initBody.apply(this, Array.prototype.slice.apply(arguments));
  318. var that = this,
  319. data = this.options.data,
  320. pageTo = this.pageTo < this.options.data.length ? this.options.data.length : this.pageTo;
  321. for (var i = this.pageFrom - 1; i < pageTo; i++) {
  322. var item = data[i];
  323. $.each(this.header.fields, function (j, field) {
  324. var value = item[field],
  325. column = that.columns[$.fn.bootstrapTable.utils.getFieldIndex(that.columns, field)];
  326. value = $.fn.bootstrapTable.utils.calculateObjectValue(that.header, that.header.formatters[j], [value, item, i], value);
  327. if ((!column.checkbox) || (!column.radio)) {
  328. if (column.filterControl !== undefined && column.filterControl.toLowerCase() === 'select' && column.searchable) {
  329. if (column.filterData === undefined || column.filterData.toLowerCase() === 'column') {
  330. var selectControl = $('.' + column.field);
  331. if (selectControl !== undefined && selectControl.length > 0) {
  332. if (selectControl.get(selectControl.length - 1).options.length === 0) {
  333. //Added the default option
  334. addOptionToSelectControl(selectControl, '', '');
  335. }
  336. //Added a new value
  337. addOptionToSelectControl(selectControl, value, value);
  338. }
  339. }
  340. }
  341. }
  342. });
  343. }
  344. };
  345. BootstrapTable.prototype.initSearch = function () {
  346. _initSearch.apply(this, Array.prototype.slice.apply(arguments));
  347. if (!this.options.sidePagination === 'server') {
  348. return;
  349. }
  350. var that = this;
  351. var fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial;
  352. //Check partial column filter
  353. this.data = fp ? $.grep(this.data, function (item, i) {
  354. for (var key in fp) {
  355. var thisColumn = that.columns[$.fn.bootstrapTable.utils.getFieldIndex(that.columns, key)];
  356. var fval = fp[key].toLowerCase();
  357. var value = item[key];
  358. // Fix #142: search use formated data
  359. if (thisColumn && thisColumn.searchFormatter) {
  360. value = $.fn.bootstrapTable.utils.calculateObjectValue(that.header,
  361. that.header.formatters[$.inArray(key, that.header.fields)],
  362. [value, item, i], value);
  363. }
  364. if (thisColumn.filterStrictSearch) {
  365. if (!($.inArray(key, that.header.fields) !== -1 &&
  366. (typeof value === 'string' || typeof value === 'number') &&
  367. value.toString().toLowerCase() === fval.toString().toLowerCase())) {
  368. return false;
  369. }
  370. }
  371. else {
  372. if (!($.inArray(key, that.header.fields) !== -1 &&
  373. (typeof value === 'string' || typeof value === 'number') &&
  374. (value + '').toLowerCase().indexOf(fval) !== -1)) {
  375. return false;
  376. }
  377. }
  378. }
  379. return true;
  380. }) : this.data;
  381. };
  382. BootstrapTable.prototype.onColumnSearch = function (event) {
  383. copyValues(this);
  384. var text = $.trim($(event.currentTarget).val());
  385. var $field = $(event.currentTarget).closest('[data-field]').data('field');
  386. if ($.isEmptyObject(this.filterColumnsPartial)) {
  387. this.filterColumnsPartial = {};
  388. }
  389. if (text) {
  390. this.filterColumnsPartial[$field] = text;
  391. } else {
  392. delete this.filterColumnsPartial[$field];
  393. }
  394. this.options.pageNumber = 1;
  395. this.onSearch(event);
  396. this.updatePagination();
  397. this.trigger('column-search', $field, text);
  398. };
  399. BootstrapTable.prototype.clearFilterControl = function () {
  400. if (this.options.filterControl && this.options.filterShowClear) {
  401. var that = this,
  402. cookies = collectBootstrapCookies(),
  403. header = getCurrentHeader(that),
  404. table = header.closest('table'),
  405. controls = header.find(getCurrentSearchControls(that)),
  406. search = that.$toolbar.find('.search input'),
  407. timeoutId = 0;
  408. $.each(that.options.valuesFilterControl, function (i, item) {
  409. item.value = '';
  410. });
  411. setValues(that);
  412. // Clear each type of filter if it exists.
  413. // Requires the body to reload each time a type of filter is found because we never know
  414. // which ones are going to be present.
  415. if (controls.length > 0) {
  416. this.filterColumnsPartial = {};
  417. $(controls[0]).trigger(controls[0].tagName === 'INPUT' ? 'keyup' : 'change');
  418. }
  419. if (search.length > 0) {
  420. that.resetSearch();
  421. }
  422. // use the default sort order if it exists. do nothing if it does not
  423. if (that.options.sortName !== table.data('sortName') || that.options.sortOrder !== table.data('sortOrder')) {
  424. var sorter = sprintf(header.find('[data-field="%s"]', $(controls[0]).closest('table').data('sortName')));
  425. that.onSort(table.data('sortName'), table.data('sortName'));
  426. $(sorter).find('.sortable').trigger('click');
  427. }
  428. // clear cookies once the filters are clean
  429. clearTimeout(timeoutId);
  430. timeoutId = setTimeout(function () {
  431. if (cookies && cookies.length > 0) {
  432. $.each(cookies, function (i, item) {
  433. that.deleteCookie(item);
  434. });
  435. }
  436. }, that.options.searchTimeOut);
  437. }
  438. };
  439. }(jQuery);