bootstrap-table-filter-control.js 21 KB

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