bootstrap-table.js 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.6.0
  4. * https://github.com/wenzhixin/bootstrap-table/
  5. */
  6. !function ($) {
  7. 'use strict';
  8. // TOOLS DEFINITION
  9. // ======================
  10. // it only does '%s', and return '' when arguments are undefined
  11. var sprintf = function(str) {
  12. var args = arguments,
  13. flag = true,
  14. i = 1;
  15. str = str.replace(/%s/g, function () {
  16. var arg = args[i++];
  17. if (typeof arg === 'undefined') {
  18. flag = false;
  19. return '';
  20. }
  21. return arg;
  22. });
  23. return flag ? str : '';
  24. };
  25. var getPropertyFromOther = function (list, from, to, value) {
  26. var result = '';
  27. $.each(list, function (i, item) {
  28. if (item[from] === value) {
  29. result = item[to];
  30. return false;
  31. }
  32. return true;
  33. });
  34. return result;
  35. };
  36. var getFieldIndex = function (columns, field) {
  37. var index = -1;
  38. $.each(columns, function (i, column) {
  39. if (column.field === field) {
  40. index = i;
  41. return false;
  42. }
  43. return true;
  44. });
  45. return index;
  46. };
  47. var getScrollBarWidth = function () {
  48. var inner = $('<p/>').addClass('fixed-table-scroll-inner'),
  49. outer = $('<div/>').addClass('fixed-table-scroll-outer'),
  50. w1, w2;
  51. outer.append(inner);
  52. $('body').append(outer);
  53. w1 = inner[0].offsetWidth;
  54. outer.css('overflow', 'scroll');
  55. w2 = inner[0].offsetWidth;
  56. if (w1 === w2) {
  57. w2 = outer[0].clientWidth;
  58. }
  59. outer.remove();
  60. return w1 - w2;
  61. };
  62. var calculateObjectValue = function (self, name, args, defaultValue) {
  63. if (typeof name === 'string') {
  64. // support obj.func1.func2
  65. var names = name.split('.');
  66. if (names.length > 1) {
  67. name = window;
  68. $.each(names, function (i, f) {
  69. name = name[f];
  70. });
  71. } else {
  72. name = window[name];
  73. }
  74. }
  75. if (typeof name === 'object') {
  76. return name;
  77. }
  78. if (typeof name === 'function') {
  79. return name.apply(self, args);
  80. }
  81. return defaultValue;
  82. };
  83. var escapeHTML = function (text) {
  84. if (typeof text === 'string') {
  85. return text
  86. .replace(/&/g, "&amp;")
  87. .replace(/</g, "&lt;")
  88. .replace(/>/g, "&gt;")
  89. .replace(/"/g, "&quot;")
  90. .replace(/'/g, "&#039;");
  91. }
  92. return text;
  93. };
  94. // BOOTSTRAP TABLE CLASS DEFINITION
  95. // ======================
  96. var BootstrapTable = function (el, options) {
  97. this.options = options;
  98. this.$el = $(el);
  99. this.$el_ = this.$el.clone();
  100. this.timeoutId_ = 0;
  101. this.init();
  102. };
  103. BootstrapTable.DEFAULTS = {
  104. classes: 'table table-hover',
  105. height: undefined,
  106. undefinedText: '-',
  107. sortName: undefined,
  108. sortOrder: 'asc',
  109. striped: false,
  110. columns: [],
  111. data: [],
  112. method: 'get',
  113. url: undefined,
  114. cache: true,
  115. contentType: 'application/json',
  116. dataType: 'json',
  117. ajaxOptions: {},
  118. queryParams: function (params) {return params;},
  119. queryParamsType: 'limit', // undefined
  120. responseHandler: function (res) {return res;},
  121. pagination: false,
  122. sidePagination: 'client', // client or server
  123. totalRows: 0, // server side need to set
  124. pageNumber: 1,
  125. pageSize: 10,
  126. pageList: [10, 25, 50, 100],
  127. search: false,
  128. searchAlign: 'right',
  129. selectItemName: 'btSelectItem',
  130. showHeader: true,
  131. showColumns: false,
  132. showPaginationSwitch: false,
  133. showRefresh: false,
  134. showToggle: false,
  135. buttonsAlign: 'right',
  136. smartDisplay: true,
  137. minimumCountColumns: 1,
  138. idField: undefined,
  139. cardView: false,
  140. trimOnSearch: true,
  141. clickToSelect: false,
  142. singleSelect: false,
  143. toolbar: undefined,
  144. toolbarAlign: 'left',
  145. checkboxHeader: true,
  146. sortable: true,
  147. maintainSelected: false,
  148. searchTimeOut: 500,
  149. iconSize: undefined,
  150. iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome)
  151. icons: {
  152. paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
  153. paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
  154. refresh: 'glyphicon-refresh icon-refresh',
  155. toggle: 'glyphicon-list-alt icon-list-alt',
  156. columns: 'glyphicon-th icon-th'
  157. },
  158. rowStyle: function (row, index) {return {};},
  159. rowAttributes: function (row, index) {return {};},
  160. onAll: function (name, args) {return false;},
  161. onClickRow: function (item, $element) {return false;},
  162. onDblClickRow: function (item, $element) {return false;},
  163. onSort: function (name, order) {return false;},
  164. onCheck: function (row) {return false;},
  165. onUncheck: function (row) {return false;},
  166. onCheckAll: function () {return false;},
  167. onUncheckAll: function () {return false;},
  168. onLoadSuccess: function (data) {return false;},
  169. onLoadError: function (status) {return false;},
  170. onColumnSwitch: function (field, checked) {return false;},
  171. onPageChange: function (number, size) {return false;},
  172. onSearch: function (text) {return false;},
  173. onPreBody: function (data) {return false;},
  174. onPostBody: function () {return false;},
  175. onPostHeader: function() {return false;}
  176. };
  177. BootstrapTable.LOCALES = [];
  178. BootstrapTable.LOCALES['en-US'] = {
  179. formatLoadingMessage: function () {
  180. return 'Loading, please wait...';
  181. },
  182. formatRecordsPerPage: function (pageNumber) {
  183. return sprintf('%s records per page', pageNumber);
  184. },
  185. formatShowingRows: function (pageFrom, pageTo, totalRows) {
  186. return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows);
  187. },
  188. formatSearch: function () {
  189. return 'Search';
  190. },
  191. formatNoMatches: function () {
  192. return 'No matching records found';
  193. },
  194. formatPaginationSwitch: function () {
  195. return 'Hide/Show pagination';
  196. },
  197. formatRefresh: function () {
  198. return 'Refresh';
  199. },
  200. formatToggle: function () {
  201. return 'Toggle';
  202. },
  203. formatColumns: function () {
  204. return 'Columns';
  205. }
  206. };
  207. $.extend(BootstrapTable.DEFAULTS, BootstrapTable.LOCALES['en-US']);
  208. BootstrapTable.COLUMN_DEFAULTS = {
  209. radio: false,
  210. checkbox: false,
  211. checkboxEnabled: true,
  212. field: undefined,
  213. title: undefined,
  214. 'class': undefined,
  215. align: undefined, // left, right, center
  216. halign: undefined, // left, right, center
  217. valign: undefined, // top, middle, bottom
  218. width: undefined,
  219. sortable: false,
  220. order: 'asc', // asc, desc
  221. visible: true,
  222. switchable: true,
  223. clickToSelect: true,
  224. formatter: undefined,
  225. events: undefined,
  226. sorter: undefined,
  227. cellStyle: undefined,
  228. searchable: true
  229. };
  230. BootstrapTable.EVENTS = {
  231. 'all.bs.table': 'onAll',
  232. 'click-row.bs.table': 'onClickRow',
  233. 'dbl-click-row.bs.table': 'onDblClickRow',
  234. 'sort.bs.table': 'onSort',
  235. 'check.bs.table': 'onCheck',
  236. 'uncheck.bs.table': 'onUncheck',
  237. 'check-all.bs.table': 'onCheckAll',
  238. 'uncheck-all.bs.table': 'onUncheckAll',
  239. 'load-success.bs.table': 'onLoadSuccess',
  240. 'load-error.bs.table': 'onLoadError',
  241. 'column-switch.bs.table': 'onColumnSwitch',
  242. 'page-change.bs.table': 'onPageChange',
  243. 'search.bs.table': 'onSearch',
  244. 'pre-body.bs.table': 'onPreBody',
  245. 'post-body.bs.table': 'onPostBody',
  246. 'post-header.bs.table' : 'onPostHeader'
  247. };
  248. BootstrapTable.prototype.init = function () {
  249. this.initContainer();
  250. this.initTable();
  251. this.initHeader();
  252. this.initData();
  253. this.initToolbar();
  254. this.initPagination();
  255. this.initBody();
  256. this.initServer();
  257. };
  258. BootstrapTable.prototype.initContainer = function () {
  259. this.$container = $([
  260. '<div class="bootstrap-table">',
  261. '<div class="fixed-table-toolbar"></div>',
  262. '<div class="fixed-table-container">',
  263. '<div class="fixed-table-header"><table></table></div>',
  264. '<div class="fixed-table-body">',
  265. '<div class="fixed-table-loading">',
  266. this.options.formatLoadingMessage(),
  267. '</div>',
  268. '</div>',
  269. '<div class="fixed-table-pagination"></div>',
  270. '</div>',
  271. '</div>'].join(''));
  272. this.$container.insertAfter(this.$el);
  273. this.$container.find('.fixed-table-body').append(this.$el);
  274. this.$container.after('<div class="clearfix"></div>');
  275. this.$loading = this.$container.find('.fixed-table-loading');
  276. this.$el.addClass(this.options.classes);
  277. if (this.options.striped) {
  278. this.$el.addClass('table-striped');
  279. }
  280. };
  281. BootstrapTable.prototype.initTable = function () {
  282. var that = this,
  283. columns = [],
  284. data = [];
  285. this.$header = this.$el.find('thead');
  286. if (!this.$header.length) {
  287. this.$header = $('<thead></thead>').appendTo(this.$el);
  288. }
  289. if (!this.$header.find('tr').length) {
  290. this.$header.append('<tr></tr>');
  291. }
  292. this.$header.find('th').each(function () {
  293. var column = $.extend({}, {
  294. title: $(this).html(),
  295. 'class': $(this).attr('class')
  296. }, $(this).data());
  297. columns.push(column);
  298. });
  299. this.options.columns = $.extend([], columns, this.options.columns);
  300. $.each(this.options.columns, function (i, column) {
  301. that.options.columns[i] = $.extend({}, BootstrapTable.COLUMN_DEFAULTS,
  302. {field: i}, column); // when field is undefined, use index instead
  303. });
  304. // if options.data is setting, do not process tbody data
  305. if (this.options.data.length) {
  306. return;
  307. }
  308. this.$el.find('tbody tr').each(function () {
  309. var row = {};
  310. // save tr's id and class
  311. row._id = $(this).attr('id');
  312. row._class = $(this).attr('class');
  313. $(this).find('td').each(function (i) {
  314. var field = that.options.columns[i].field;
  315. row[field] = $(this).html();
  316. // save td's id and class
  317. row['_' + field + '_id'] = $(this).attr('id');
  318. row['_' + field + '_class'] = $(this).attr('class');
  319. });
  320. data.push(row);
  321. });
  322. this.options.data = data;
  323. };
  324. BootstrapTable.prototype.initHeader = function () {
  325. var that = this,
  326. visibleColumns = [],
  327. html = [];
  328. this.header = {
  329. fields: [],
  330. styles: [],
  331. classes: [],
  332. formatters: [],
  333. events: [],
  334. sorters: [],
  335. cellStyles: [],
  336. clickToSelects: [],
  337. searchables: []
  338. };
  339. $.each(this.options.columns, function (i, column) {
  340. var text = '',
  341. halign = '', // header align style
  342. align = '', // body align style
  343. style = '',
  344. class_ = sprintf(' class="%s"', column['class']),
  345. order = that.options.sortOrder || column.order,
  346. searchable = true;
  347. if (!column.visible) {
  348. return;
  349. }
  350. halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align);
  351. align = sprintf('text-align: %s; ', column.align);
  352. style = sprintf('vertical-align: %s; ', column.valign);
  353. style += sprintf('width: %spx; ', column.checkbox || column.radio ? 36 : column.width);
  354. visibleColumns.push(column);
  355. that.header.fields.push(column.field);
  356. that.header.styles.push(align + style);
  357. that.header.classes.push(class_);
  358. that.header.formatters.push(column.formatter);
  359. that.header.events.push(column.events);
  360. that.header.sorters.push(column.sorter);
  361. that.header.cellStyles.push(column.cellStyle);
  362. that.header.clickToSelects.push(column.clickToSelect);
  363. that.header.searchables.push(column.searchable);
  364. html.push('<th',
  365. column.checkbox || column.radio ?
  366. sprintf(' class="bs-checkbox %s"', column['class'] || '') :
  367. class_,
  368. sprintf(' style="%s"', halign + style),
  369. '>');
  370. html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ?
  371. 'sortable' : ''));
  372. text = column.title;
  373. if (that.options.sortName === column.field && that.options.sortable && column.sortable) {
  374. text += that.getCaretHtml();
  375. }
  376. if (column.checkbox) {
  377. if (!that.options.singleSelect && that.options.checkboxHeader) {
  378. text = '<input name="btSelectAll" type="checkbox" />';
  379. }
  380. that.header.stateField = column.field;
  381. }
  382. if (column.radio) {
  383. text = '';
  384. that.header.stateField = column.field;
  385. that.options.singleSelect = true;
  386. }
  387. html.push(text);
  388. html.push('</div>');
  389. html.push('<div class="fht-cell"></div>');
  390. html.push('</th>');
  391. });
  392. this.$header.find('tr').html(html.join(''));
  393. this.$header.find('th').each(function (i) {
  394. $(this).data(visibleColumns[i]);
  395. });
  396. this.$container.off('click', 'th').on('click', 'th', function (event) {
  397. if (that.options.sortable && $(this).data().sortable) {
  398. that.onSort(event);
  399. }
  400. });
  401. if (!this.options.showHeader || this.options.cardView) {
  402. this.$header.hide();
  403. this.$container.find('.fixed-table-header').hide();
  404. this.$loading.css('top', 0);
  405. } else {
  406. this.$header.show();
  407. this.$container.find('.fixed-table-header').show();
  408. this.$loading.css('top', '37px');
  409. }
  410. this.$selectAll = this.$header.find('[name="btSelectAll"]');
  411. this.$container.off('click', '[name="btSelectAll"]')
  412. .on('click', '[name="btSelectAll"]', function () {
  413. var checked = $(this).prop('checked');
  414. that[checked ? 'checkAll' : 'uncheckAll']();
  415. });
  416. };
  417. /**
  418. * @param data
  419. * @param type: append / prepend
  420. */
  421. BootstrapTable.prototype.initData = function (data, type) {
  422. if (type === 'append') {
  423. this.data = this.data.concat(data);
  424. } else if (type === 'prepend') {
  425. this.data = [].concat(data).concat(this.data);
  426. } else {
  427. this.data = data || this.options.data;
  428. }
  429. this.options.data = this.data;
  430. if (this.options.sidePagination === 'server') {
  431. return;
  432. }
  433. this.initSort();
  434. };
  435. BootstrapTable.prototype.initSort = function () {
  436. var that = this,
  437. name = this.options.sortName,
  438. order = this.options.sortOrder === 'desc' ? -1 : 1,
  439. index = $.inArray(this.options.sortName, this.header.fields);
  440. if (index !== -1) {
  441. this.data.sort(function (a, b) {
  442. var aa = a[name],
  443. bb = b[name],
  444. value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]);
  445. if (value !== undefined) {
  446. return order * value;
  447. }
  448. // Convert numerical values form string to float.
  449. if ($.isNumeric(aa)) {
  450. aa = parseFloat(aa);
  451. }
  452. if ($.isNumeric(bb)) {
  453. bb = parseFloat(bb);
  454. }
  455. // Fix #161: undefined or null string sort bug.
  456. if (aa === undefined || aa === null) {
  457. aa = '';
  458. }
  459. if (bb === undefined || bb === null) {
  460. bb = '';
  461. }
  462. if ($.isNumeric(aa) && $.isNumeric(bb)) {
  463. if (aa < bb) {
  464. return order * -1;
  465. }
  466. return order;
  467. }
  468. if (aa === bb) {
  469. return 0;
  470. }
  471. if (aa.localeCompare(bb) === -1) {
  472. return order * -1;
  473. }
  474. return order;
  475. });
  476. }
  477. };
  478. BootstrapTable.prototype.onSort = function (event) {
  479. var $this = $(event.currentTarget),
  480. $this_ = this.$header.find('th').eq($this.index());
  481. this.$header.add(this.$header_).find('span.order').remove();
  482. if (this.options.sortName === $this.data('field')) {
  483. this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc';
  484. } else {
  485. this.options.sortName = $this.data('field');
  486. this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
  487. }
  488. this.trigger('sort', this.options.sortName, this.options.sortOrder);
  489. $this.add($this_).data('order', this.options.sortOrder)
  490. .find('.th-inner').append(this.getCaretHtml());
  491. if (this.options.sidePagination === 'server') {
  492. this.initServer();
  493. return;
  494. }
  495. this.initSort();
  496. this.initBody();
  497. };
  498. BootstrapTable.prototype.initToolbar = function () {
  499. var that = this,
  500. html = [],
  501. timeoutId = 0,
  502. $keepOpen,
  503. $search,
  504. switchableCount = 0;
  505. this.$toolbar = this.$container.find('.fixed-table-toolbar').html('');
  506. if (typeof this.options.toolbar === 'string') {
  507. $(sprintf('<div class="bars pull-%s"></div>', this.options.toolbarAlign))
  508. .appendTo(this.$toolbar)
  509. .append($(this.options.toolbar));
  510. }
  511. // showColumns, showToggle, showRefresh
  512. html = [sprintf('<div class="columns columns-%s btn-group pull-%s">',
  513. this.options.buttonsAlign, this.options.buttonsAlign)];
  514. if (typeof this.options.icons === 'string') {
  515. this.options.icons = calculateObjectValue(null, this.options.icons);
  516. }
  517. if (this.options.showPaginationSwitch) {
  518. html.push(sprintf('<button class="btn btn-default" type="button" name="paginationSwitch" title="%s">',
  519. this.options.formatPaginationSwitch()),
  520. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown),
  521. '</button>');
  522. }
  523. if (this.options.showRefresh) {
  524. html.push(sprintf('<button class="btn btn-default' + (this.options.iconSize == undefined ? '' : ' btn-' + this.options.iconSize) + '" type="button" name="refresh" title="%s">',
  525. this.options.formatRefresh()),
  526. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh),
  527. '</button>');
  528. }
  529. if (this.options.showToggle) {
  530. html.push(sprintf('<button class="btn btn-default' + (this.options.iconSize == undefined ? '' : ' btn-' + this.options.iconSize) + '" type="button" name="toggle" title="%s">',
  531. this.options.formatToggle()),
  532. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggle),
  533. '</button>');
  534. }
  535. if (this.options.showColumns) {
  536. html.push(sprintf('<div class="keep-open btn-group" title="%s">',
  537. this.options.formatColumns()),
  538. '<button type="button" class="btn btn-default' + (this.options.iconSize == undefined ? '' : ' btn-' + this.options.iconSize) + ' dropdown-toggle" data-toggle="dropdown">',
  539. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns),
  540. ' <span class="caret"></span>',
  541. '</button>',
  542. '<ul class="dropdown-menu" role="menu">');
  543. $.each(this.options.columns, function (i, column) {
  544. if (column.radio || column.checkbox) {
  545. return;
  546. }
  547. var checked = column.visible ? ' checked="checked"' : '';
  548. if (column.switchable) {
  549. html.push(sprintf('<li>' +
  550. '<label><input type="checkbox" data-field="%s" value="%s"%s> %s</label>' +
  551. '</li>', column.field, i, checked, column.title));
  552. switchableCount++;
  553. }
  554. });
  555. html.push('</ul>',
  556. '</div>');
  557. }
  558. html.push('</div>');
  559. // Fix #188: this.showToolbar is for extentions
  560. if (this.showToolbar || html.length > 2) {
  561. this.$toolbar.append(html.join(''));
  562. }
  563. if (this.options.showPaginationSwitch) {
  564. this.$toolbar.find('button[name="paginationSwitch"]')
  565. .off('click').on('click', $.proxy(this.togglePagination, this));
  566. }
  567. if (this.options.showRefresh) {
  568. this.$toolbar.find('button[name="refresh"]')
  569. .off('click').on('click', $.proxy(this.refresh, this));
  570. }
  571. if (this.options.showToggle) {
  572. this.$toolbar.find('button[name="toggle"]')
  573. .off('click').on('click', function () {
  574. that.options.cardView = !that.options.cardView;
  575. that.initHeader();
  576. that.initBody();
  577. });
  578. }
  579. if (this.options.showColumns) {
  580. $keepOpen = this.$toolbar.find('.keep-open');
  581. if (switchableCount <= this.options.minimumCountColumns) {
  582. $keepOpen.find('input').prop('disabled', true);
  583. }
  584. $keepOpen.find('li').off('click').on('click', function (event) {
  585. event.stopImmediatePropagation();
  586. });
  587. $keepOpen.find('input').off('click').on('click', function () {
  588. var $this = $(this);
  589. that.toggleColumn($this.val(), $this.prop('checked'), false);
  590. that.trigger('column-switch', $(this).data('field'), $this.prop('checked'));
  591. });
  592. }
  593. if (this.options.search) {
  594. html = [];
  595. html.push(
  596. '<div class="pull-' + this.options.searchAlign + ' search">',
  597. sprintf('<input class="form-control' + (this.options.iconSize == undefined ? '' : ' input-' + this.options.iconSize) + '" type="text" placeholder="%s">',
  598. this.options.formatSearch()),
  599. '</div>');
  600. this.$toolbar.append(html.join(''));
  601. $search = this.$toolbar.find('.search input');
  602. $search.off('keyup').on('keyup', function (event) {
  603. clearTimeout(timeoutId); // doesn't matter if it's 0
  604. timeoutId = setTimeout(function () {
  605. that.onSearch(event);
  606. }, that.options.searchTimeOut);
  607. });
  608. }
  609. };
  610. BootstrapTable.prototype.onSearch = function (event) {
  611. var text = $.trim($(event.currentTarget).val());
  612. // trim search input
  613. if(this.options.trimOnSearch) {
  614. $(event.currentTarget).val(text);
  615. }
  616. if (text === this.searchText) {
  617. return;
  618. }
  619. this.searchText = text;
  620. this.options.pageNumber = 1;
  621. this.initSearch();
  622. this.updatePagination();
  623. this.trigger('search', text);
  624. };
  625. BootstrapTable.prototype.initSearch = function () {
  626. var that = this;
  627. if (this.options.sidePagination !== 'server') {
  628. var s = this.searchText && this.searchText.toLowerCase();
  629. var f = $.isEmptyObject(this.filterColumns) ? null: this.filterColumns;
  630. // Check filter
  631. this.data = f ? $.grep(this.options.data, function (item, i) {
  632. for (var key in f) {
  633. if (item[key] !== f[key]) {
  634. return false;
  635. }
  636. }
  637. return true;
  638. }) : this.options.data;
  639. this.data = s ? $.grep(this.data, function (item, i) {
  640. for (var key in item) {
  641. key = $.isNumeric(key) ? parseInt(key, 10) : key;
  642. var value = item[key];
  643. // Fix #142: search use formated data
  644. value = calculateObjectValue(that.header,
  645. that.header.formatters[$.inArray(key, that.header.fields)],
  646. [value, item, i], value);
  647. var index = $.inArray(key, that.header.fields);
  648. if (index !== -1 && that.header.searchables[index] &&
  649. (typeof value === 'string' ||
  650. typeof value === 'number') &&
  651. (value + '').toLowerCase().indexOf(s) !== -1) {
  652. return true;
  653. }
  654. }
  655. return false;
  656. }) : this.data;
  657. }
  658. };
  659. BootstrapTable.prototype.initPagination = function () {
  660. this.$pagination = this.$container.find('.fixed-table-pagination');
  661. if (!this.options.pagination) {
  662. this.$pagination.hide();
  663. return;
  664. } else {
  665. this.$pagination.show();
  666. }
  667. var that = this,
  668. html = [],
  669. i, from, to,
  670. $pageList,
  671. $first, $pre,
  672. $next, $last,
  673. $number,
  674. data = this.getData();
  675. if (this.options.sidePagination !== 'server') {
  676. this.options.totalRows = data.length;
  677. }
  678. this.totalPages = 0;
  679. if (this.options.totalRows) {
  680. this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
  681. this.options.totalPages = this.totalPages;
  682. }
  683. if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
  684. this.options.pageNumber = this.totalPages;
  685. }
  686. this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
  687. this.pageTo = this.options.pageNumber * this.options.pageSize;
  688. if (this.pageTo > this.options.totalRows) {
  689. this.pageTo = this.options.totalRows;
  690. }
  691. html.push(
  692. '<div class="pull-left pagination-detail">',
  693. '<span class="pagination-info">',
  694. this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
  695. '</span>');
  696. html.push('<span class="page-list">');
  697. var pageNumber = [
  698. '<span class="btn-group dropup">',
  699. '<button type="button" class="btn btn-default '+ (this.options.iconSize == undefined ? '' : ' btn-' + this.options.iconSize)+ ' dropdown-toggle" data-toggle="dropdown">',
  700. '<span class="page-size">',
  701. this.options.pageSize,
  702. '</span>',
  703. ' <span class="caret"></span>',
  704. '</button>',
  705. '<ul class="dropdown-menu" role="menu">'],
  706. pageList = this.options.pageList;
  707. if (typeof this.options.pageList === 'string') {
  708. var list = this.options.pageList.replace('[', '').replace(']', '').replace(/ /g, '').split(',');
  709. pageList = [];
  710. $.each(list, function (i, value) {
  711. pageList.push(+value);
  712. });
  713. }
  714. $.each(pageList, function (i, page) {
  715. if (!that.options.smartDisplay || i === 0 || pageList[i-1] <= that.options.totalRows) {
  716. var active = page === that.options.pageSize ? ' class="active"' : '';
  717. pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page));
  718. }
  719. });
  720. pageNumber.push('</ul></span>');
  721. html.push(this.options.formatRecordsPerPage(pageNumber.join('')));
  722. html.push('</span>');
  723. html.push('</div>',
  724. '<div class="pull-right pagination">',
  725. '<ul class="pagination' + (this.options.iconSize == undefined ? '' : ' pagination-' + this.options.iconSize) + '">',
  726. '<li class="page-first"><a href="javascript:void(0)">&lt;&lt;</a></li>',
  727. '<li class="page-pre"><a href="javascript:void(0)">&lt;</a></li>');
  728. if (this.totalPages < 5) {
  729. from = 1;
  730. to = this.totalPages;
  731. } else {
  732. from = this.options.pageNumber - 2;
  733. to = from + 4;
  734. if (from < 1) {
  735. from = 1;
  736. to = 5;
  737. }
  738. if (to > this.totalPages) {
  739. to = this.totalPages;
  740. from = to - 4;
  741. }
  742. }
  743. for (i = from; i <= to; i++) {
  744. html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
  745. '<a href="javascript:void(0)">', i ,'</a>',
  746. '</li>');
  747. }
  748. html.push(
  749. '<li class="page-next"><a href="javascript:void(0)">&gt;</a></li>',
  750. '<li class="page-last"><a href="javascript:void(0)">&gt;&gt;</a></li>',
  751. '</ul>',
  752. '</div>');
  753. this.$pagination.html(html.join(''));
  754. $pageList = this.$pagination.find('.page-list a');
  755. $first = this.$pagination.find('.page-first');
  756. $pre = this.$pagination.find('.page-pre');
  757. $next = this.$pagination.find('.page-next');
  758. $last = this.$pagination.find('.page-last');
  759. $number = this.$pagination.find('.page-number');
  760. if (this.options.pageNumber <= 1) {
  761. $first.addClass('disabled');
  762. $pre.addClass('disabled');
  763. }
  764. if (this.options.pageNumber >= this.totalPages) {
  765. $next.addClass('disabled');
  766. $last.addClass('disabled');
  767. }
  768. if (this.options.smartDisplay) {
  769. if (this.totalPages <= 1) {
  770. this.$pagination.find('div.pagination').hide();
  771. }
  772. if (this.options.pageList.length < 2 || this.options.totalRows <= this.options.pageList[0]) {
  773. this.$pagination.find('span.page-list').hide();
  774. }
  775. // when data is empty, hide the pagination
  776. this.$pagination[this.getData().length ? 'show' : 'hide']();
  777. }
  778. $pageList.off('click').on('click', $.proxy(this.onPageListChange, this));
  779. $first.off('click').on('click', $.proxy(this.onPageFirst, this));
  780. $pre.off('click').on('click', $.proxy(this.onPagePre, this));
  781. $next.off('click').on('click', $.proxy(this.onPageNext, this));
  782. $last.off('click').on('click', $.proxy(this.onPageLast, this));
  783. $number.off('click').on('click', $.proxy(this.onPageNumber, this));
  784. };
  785. BootstrapTable.prototype.updatePagination = function (event) {
  786. // Fix #171: IE disabled button can be clicked bug.
  787. if (event && $(event.currentTarget).hasClass('disabled')) {
  788. return;
  789. }
  790. if (!this.options.maintainSelected) {
  791. this.resetRows();
  792. }
  793. this.initPagination();
  794. if (this.options.sidePagination === 'server') {
  795. this.initServer();
  796. } else {
  797. this.initBody();
  798. }
  799. this.trigger('page-change', this.options.pageNumber, this.options.pageSize);
  800. };
  801. BootstrapTable.prototype.onPageListChange = function (event) {
  802. var $this = $(event.currentTarget);
  803. $this.parent().addClass('active').siblings().removeClass('active');
  804. this.options.pageSize = +$this.text();
  805. this.$toolbar.find('.page-size').text(this.options.pageSize);
  806. this.updatePagination(event);
  807. };
  808. BootstrapTable.prototype.onPageFirst = function (event) {
  809. this.options.pageNumber = 1;
  810. this.updatePagination(event);
  811. };
  812. BootstrapTable.prototype.onPagePre = function (event) {
  813. this.options.pageNumber--;
  814. this.updatePagination(event);
  815. };
  816. BootstrapTable.prototype.onPageNext = function (event) {
  817. this.options.pageNumber++;
  818. this.updatePagination(event);
  819. };
  820. BootstrapTable.prototype.onPageLast = function (event) {
  821. this.options.pageNumber = this.totalPages;
  822. this.updatePagination(event);
  823. };
  824. BootstrapTable.prototype.onPageNumber = function (event) {
  825. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  826. return;
  827. }
  828. this.options.pageNumber = +$(event.currentTarget).text();
  829. this.updatePagination(event);
  830. };
  831. BootstrapTable.prototype.initBody = function (fixedScroll) {
  832. var that = this,
  833. html = [],
  834. data = this.getData();
  835. this.trigger('pre-body', data);
  836. this.$body = this.$el.find('tbody');
  837. if (!this.$body.length) {
  838. this.$body = $('<tbody></tbody>').appendTo(this.$el);
  839. }
  840. //Fix #389 Bootstrap-table-flatJSON is not working
  841. if (!this.options.pagination || this.options.sidePagination === 'server') {
  842. this.pageFrom = 1;
  843. this.pageTo = data.length;
  844. }
  845. for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
  846. var item = data[i],
  847. style = {},
  848. csses = [],
  849. attributes = {},
  850. htmlAttributes = [];
  851. style = calculateObjectValue(this.options, this.options.rowStyle, [item, i], style);
  852. if (style && style.css) {
  853. for (var key in style.css) {
  854. csses.push(key + ': ' + style.css[key]);
  855. }
  856. }
  857. attributes = calculateObjectValue(this.options,
  858. this.options.rowAttributes, [item, i], attributes);
  859. if (attributes) {
  860. for (var key in attributes) {
  861. htmlAttributes.push(sprintf('%s="%s"', key, escapeHTML(attributes[key])));
  862. }
  863. }
  864. html.push('<tr',
  865. sprintf(' %s', htmlAttributes.join(' ')),
  866. sprintf(' id="%s"', $.isArray(item) ? undefined : item._id),
  867. sprintf(' class="%s"', style.classes || ($.isArray(item) ? undefined : item._class)),
  868. sprintf(' data-index="%s"', i),
  869. '>'
  870. );
  871. if (this.options.cardView) {
  872. html.push(sprintf('<td colspan="%s">', this.header.fields.length));
  873. }
  874. $.each(this.header.fields, function (j, field) {
  875. var text = '',
  876. value = item[field],
  877. type = '',
  878. cellStyle = {},
  879. id_ = '',
  880. class_ = that.header.classes[j],
  881. column = that.options.columns[getFieldIndex(that.options.columns, field)];
  882. style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
  883. value = calculateObjectValue(that.header,
  884. that.header.formatters[j], [value, item, i], value);
  885. // handle td's id and class
  886. if (item['_' + field + '_id']) {
  887. id_ = sprintf(' id="%s"', item['_' + field + '_id']);
  888. }
  889. if (item['_' + field + '_class']) {
  890. class_ = sprintf(' class="%s"', item['_' + field + '_class']);
  891. }
  892. cellStyle = calculateObjectValue(that.header,
  893. that.header.cellStyles[j], [value, item, i], cellStyle);
  894. if (cellStyle.classes) {
  895. class_ = sprintf(' class="%s"', cellStyle.classes);
  896. }
  897. if (cellStyle.css) {
  898. var csses_ = [];
  899. for (var key in cellStyle.css) {
  900. csses_.push(key + ': ' + cellStyle.css[key]);
  901. }
  902. style = sprintf('style="%s"', csses_.concat(that.header.styles[j]).join('; '));
  903. }
  904. if (column.checkbox || column.radio) {
  905. type = column.checkbox ? 'checkbox' : type;
  906. type = column.radio ? 'radio' : type;
  907. text = [that.options.cardView ?
  908. '<div class="card-view">' : '<td class="bs-checkbox">',
  909. '<input' +
  910. sprintf(' data-index="%s"', i) +
  911. sprintf(' name="%s"', that.options.selectItemName) +
  912. sprintf(' type="%s"', type) +
  913. sprintf(' value="%s"', item[that.options.idField]) +
  914. sprintf(' checked="%s"', value === true ||
  915. (value && value.checked) ? 'checked' : undefined) +
  916. sprintf(' disabled="%s"', !column.checkboxEnabled ||
  917. (value && value.disabled) ? 'disabled' : undefined) +
  918. ' />',
  919. that.options.cardView ? '</div>' : '</td>'].join('');
  920. } else {
  921. value = typeof value === 'undefined' || value === null ?
  922. that.options.undefinedText : value;
  923. text = that.options.cardView ?
  924. ['<div class="card-view">',
  925. that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style,
  926. getPropertyFromOther(that.options.columns, 'field', 'title', field)) : '',
  927. sprintf('<span class="value">%s</span>', value),
  928. '</div>'].join('') :
  929. [sprintf('<td%s %s %s>', id_, class_, style),
  930. value,
  931. '</td>'].join('');
  932. // Hide empty data on Card view when smartDisplay is set to true.
  933. if (that.options.cardView && that.options.smartDisplay && value === '') {
  934. text = '';
  935. }
  936. }
  937. html.push(text);
  938. });
  939. if (this.options.cardView) {
  940. html.push('</td>');
  941. }
  942. html.push('</tr>');
  943. }
  944. // show no records
  945. if (!html.length) {
  946. html.push('<tr class="no-records-found">',
  947. sprintf('<td colspan="%s">%s</td>', this.header.fields.length, this.options.formatNoMatches()),
  948. '</tr>');
  949. }
  950. this.$body.html(html.join(''));
  951. if (!fixedScroll) {
  952. this.scrollTo(0);
  953. }
  954. // click to select by column
  955. this.$body.find('> tr > td').off('click').on('click', function () {
  956. var $tr = $(this).parent();
  957. that.trigger('click-row', that.data[$tr.data('index')], $tr);
  958. // if click to select - then trigger the checkbox/radio click
  959. if (that.options.clickToSelect) {
  960. if (that.header.clickToSelects[$tr.children().index($(this))]) {
  961. $tr.find(sprintf('[name="%s"]',
  962. that.options.selectItemName))[0].click(); // #144: .trigger('click') bug
  963. }
  964. }
  965. });
  966. this.$body.find('tr').off('dblclick').on('dblclick', function () {
  967. that.trigger('dbl-click-row', that.data[$(this).data('index')], $(this));
  968. });
  969. this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
  970. this.$selectItem.off('click').on('click', function (event) {
  971. event.stopImmediatePropagation();
  972. var checked = $(this).prop('checked'),
  973. row = that.data[$(this).data('index')];
  974. row[that.header.stateField] = checked;
  975. that.trigger(checked ? 'check' : 'uncheck', row);
  976. if (that.options.singleSelect) {
  977. that.$selectItem.not(this).each(function () {
  978. that.data[$(this).data('index')][that.header.stateField] = false;
  979. });
  980. that.$selectItem.filter(':checked').not(this).prop('checked', false);
  981. }
  982. that.updateSelected();
  983. });
  984. $.each(this.header.events, function (i, events) {
  985. if (!events) {
  986. return;
  987. }
  988. // fix bug, if events is defined with namespace
  989. if (typeof events === 'string') {
  990. events = calculateObjectValue(null, events);
  991. }
  992. for (var key in events) {
  993. that.$body.find('tr').each(function () {
  994. var $tr = $(this),
  995. $td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(i),
  996. index = key.indexOf(' '),
  997. name = key.substring(0, index),
  998. el = key.substring(index + 1),
  999. func = events[key];
  1000. $td.find(el).off(name).on(name, function (e) {
  1001. var index = $tr.data('index'),
  1002. row = that.data[index],
  1003. value = row[that.header.fields[i]];
  1004. func.apply(this, [e, value, row, index]);
  1005. });
  1006. });
  1007. }
  1008. });
  1009. this.updateSelected();
  1010. this.resetView();
  1011. this.trigger('post-body');
  1012. };
  1013. BootstrapTable.prototype.initServer = function (silent, query) {
  1014. var that = this,
  1015. data = {},
  1016. params = {
  1017. pageSize: this.options.pageSize,
  1018. pageNumber: this.options.pageNumber,
  1019. searchText: this.searchText,
  1020. sortName: this.options.sortName,
  1021. sortOrder: this.options.sortOrder
  1022. };
  1023. if (!this.options.url) {
  1024. return;
  1025. }
  1026. if (this.options.queryParamsType === 'limit') {
  1027. params = {
  1028. search: params.searchText,
  1029. sort: params.sortName,
  1030. order: params.sortOrder
  1031. };
  1032. if (this.options.pagination) {
  1033. params.limit = this.options.pageSize;
  1034. params.offset = this.options.pageSize * (this.options.pageNumber - 1);
  1035. }
  1036. }
  1037. data = calculateObjectValue(this.options, this.options.queryParams, [params], data);
  1038. $.extend(data, query || {});
  1039. // false to stop request
  1040. if (data === false) {
  1041. return;
  1042. }
  1043. if (!silent) {
  1044. this.$loading.show();
  1045. }
  1046. $.ajax($.extend({}, calculateObjectValue(null, this.options.ajaxOptions), {
  1047. type: this.options.method,
  1048. url: this.options.url,
  1049. data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
  1050. JSON.stringify(data): data,
  1051. cache: this.options.cache,
  1052. contentType: this.options.contentType,
  1053. dataType: this.options.dataType,
  1054. success: function (res) {
  1055. res = calculateObjectValue(that.options, that.options.responseHandler, [res], res);
  1056. that.load(res);
  1057. that.trigger('load-success', res);
  1058. },
  1059. error: function (res) {
  1060. that.trigger('load-error', res.status);
  1061. },
  1062. complete: function () {
  1063. if (!silent) {
  1064. that.$loading.hide();
  1065. }
  1066. }
  1067. }));
  1068. };
  1069. BootstrapTable.prototype.getCaretHtml = function () {
  1070. return ['<span class="order' + (this.options.sortOrder === 'desc' ? '' : ' dropup') + '">',
  1071. '<span class="caret" style="margin: 10px 5px;"></span>',
  1072. '</span>'].join('');
  1073. };
  1074. BootstrapTable.prototype.updateSelected = function () {
  1075. var checkAll = this.$selectItem.filter(':enabled').length ===
  1076. this.$selectItem.filter(':enabled').filter(':checked').length;
  1077. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll);
  1078. this.$selectItem.each(function () {
  1079. $(this).parents('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
  1080. });
  1081. };
  1082. BootstrapTable.prototype.updateRows = function (checked) {
  1083. var that = this;
  1084. this.$selectItem.each(function () {
  1085. that.data[$(this).data('index')][that.header.stateField] = checked;
  1086. });
  1087. };
  1088. BootstrapTable.prototype.resetRows = function () {
  1089. var that = this;
  1090. $.each(this.data, function (i, row) {
  1091. that.$selectAll.prop('checked', false);
  1092. that.$selectItem.prop('checked', false);
  1093. row[that.header.stateField] = false;
  1094. });
  1095. };
  1096. BootstrapTable.prototype.trigger = function (name) {
  1097. var args = Array.prototype.slice.call(arguments, 1);
  1098. name += '.bs.table';
  1099. this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
  1100. this.$el.trigger($.Event(name), args);
  1101. this.options.onAll(name, args);
  1102. this.$el.trigger($.Event('all.bs.table'), [name, args]);
  1103. };
  1104. BootstrapTable.prototype.resetHeader = function () {
  1105. var that = this,
  1106. $fixedHeader = this.$container.find('.fixed-table-header'),
  1107. $fixedBody = this.$container.find('.fixed-table-body'),
  1108. scrollWidth = this.$el.width() > $fixedBody.width() ? getScrollBarWidth() : 0;
  1109. // fix #61: the hidden table reset header bug.
  1110. if (this.$el.is(':hidden')) {
  1111. clearTimeout(this.timeoutId_); // doesn't matter if it's 0
  1112. this.timeoutId_ = setTimeout($.proxy(this.resetHeader, this), 100); // 100ms
  1113. return;
  1114. }
  1115. this.$header_ = this.$header.clone(true, true);
  1116. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
  1117. // fix bug: get $el.css('width') error sometime (height = 500)
  1118. setTimeout(function () {
  1119. $fixedHeader.css({
  1120. 'height': '37px',
  1121. 'border-bottom': '1px solid #dddddd',
  1122. 'margin-right': scrollWidth
  1123. }).find('table').css('width', that.$el.css('width'))
  1124. .html('').attr('class', that.$el.attr('class'))
  1125. .append(that.$header_);
  1126. // fix bug: $.data() is not working as expected after $.append()
  1127. that.$header.find('th').each(function (i) {
  1128. that.$header_.find('th').eq(i).data($(this).data());
  1129. });
  1130. that.$body.find('tr:first-child:not(.no-records-found) > *').each(function(i) {
  1131. that.$header_.find('div.fht-cell').eq(i).width($(this).innerWidth());
  1132. });
  1133. that.$el.css('margin-top', -that.$header.height());
  1134. // horizontal scroll event
  1135. $fixedBody.off('scroll').on('scroll', function () {
  1136. $fixedHeader.scrollLeft($(this).scrollLeft());
  1137. });
  1138. that.trigger('post-header');
  1139. });
  1140. };
  1141. BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
  1142. if (index === -1) {
  1143. return;
  1144. }
  1145. this.options.columns[index].visible = checked;
  1146. this.initHeader();
  1147. this.initSearch();
  1148. this.initPagination();
  1149. this.initBody();
  1150. if (this.options.showColumns) {
  1151. var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
  1152. if (needUpdate) {
  1153. $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
  1154. }
  1155. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  1156. $items.filter(':checked').prop('disabled', true);
  1157. }
  1158. }
  1159. };
  1160. // PUBLIC FUNCTION DEFINITION
  1161. // =======================
  1162. BootstrapTable.prototype.resetView = function (params) {
  1163. var that = this,
  1164. header = this.header;
  1165. if (params && params.height) {
  1166. this.options.height = params.height;
  1167. }
  1168. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  1169. this.$selectItem.length === this.$selectItem.filter(':checked').length);
  1170. if (this.options.height) {
  1171. var toolbarHeight = +this.$toolbar.children().outerHeight(true),
  1172. paginationHeight = +this.$pagination.children().outerHeight(true),
  1173. height = this.options.height - toolbarHeight - paginationHeight;
  1174. this.$container.find('.fixed-table-container').css('height', height + 'px');
  1175. }
  1176. if (this.options.cardView) {
  1177. // remove the element css
  1178. that.$el.css('margin-top', '0');
  1179. that.$container.find('.fixed-table-container').css('padding-bottom', '0');
  1180. return;
  1181. }
  1182. if (this.options.showHeader && this.options.height) {
  1183. this.resetHeader();
  1184. } else {
  1185. this.trigger('post-header');
  1186. }
  1187. if (this.options.height && this.options.showHeader) {
  1188. this.$container.find('.fixed-table-container').css('padding-bottom', '37px');
  1189. }
  1190. };
  1191. BootstrapTable.prototype.getData = function () {
  1192. return (this.searchText || !$.isEmptyObject(this.filterColumns)) ? this.data : this.options.data;
  1193. };
  1194. BootstrapTable.prototype.load = function (data) {
  1195. // #431: support pagination
  1196. if (this.options.sidePagination === 'server') {
  1197. this.options.totalRows = data.total;
  1198. data = data.rows;
  1199. }
  1200. this.initData(data);
  1201. this.initSearch();
  1202. this.initPagination();
  1203. this.initBody();
  1204. };
  1205. BootstrapTable.prototype.append = function (data) {
  1206. this.initData(data, 'append');
  1207. this.initSearch();
  1208. this.initPagination();
  1209. this.initBody(true);
  1210. };
  1211. BootstrapTable.prototype.prepend = function (data) {
  1212. this.initData(data, 'prepend');
  1213. this.initSearch();
  1214. this.initPagination();
  1215. this.initBody(true);
  1216. };
  1217. BootstrapTable.prototype.remove = function (params) {
  1218. var len = this.options.data.length,
  1219. i, row;
  1220. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  1221. return;
  1222. }
  1223. for (i = len - 1; i >= 0; i--) {
  1224. row = this.options.data[i];
  1225. if (!row.hasOwnProperty(params.field)) {
  1226. return;
  1227. }
  1228. if ($.inArray(row[params.field], params.values) !== -1) {
  1229. this.options.data.splice(i, 1);
  1230. }
  1231. }
  1232. if (len === this.options.data.length) {
  1233. return;
  1234. }
  1235. this.initSearch();
  1236. this.initPagination();
  1237. this.initBody(true);
  1238. };
  1239. BootstrapTable.prototype.insertRow = function (params) {
  1240. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1241. return;
  1242. }
  1243. this.data.splice(params.index, 0, params.row);
  1244. this.initBody(true);
  1245. };
  1246. BootstrapTable.prototype.updateRow = function (params) {
  1247. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1248. return;
  1249. }
  1250. $.extend(this.data[params.index], params.row);
  1251. this.initBody(true);
  1252. };
  1253. BootstrapTable.prototype.mergeCells = function (options) {
  1254. var row = options.index,
  1255. col = $.inArray(options.field, this.header.fields),
  1256. rowspan = options.rowspan || 1,
  1257. colspan = options.colspan || 1,
  1258. i, j,
  1259. $tr = this.$body.find('tr'),
  1260. $td = $tr.eq(row).find('td').eq(col);
  1261. if (row < 0 || col < 0 || row >= this.data.length) {
  1262. return;
  1263. }
  1264. for (i = row; i < row + rowspan; i++) {
  1265. for (j = col; j < col + colspan; j++) {
  1266. $tr.eq(i).find('td').eq(j).hide();
  1267. }
  1268. }
  1269. $td.attr('rowspan', rowspan).attr('colspan', colspan).show();
  1270. };
  1271. BootstrapTable.prototype.getOptions = function () {
  1272. return this.options;
  1273. };
  1274. BootstrapTable.prototype.getSelections = function () {
  1275. var that = this;
  1276. return $.grep(this.data, function (row) {
  1277. return row[that.header.stateField];
  1278. });
  1279. };
  1280. BootstrapTable.prototype.checkAll = function () {
  1281. this.checkAll_(true);
  1282. };
  1283. BootstrapTable.prototype.uncheckAll = function () {
  1284. this.checkAll_(false);
  1285. };
  1286. BootstrapTable.prototype.checkAll_ = function (checked) {
  1287. this.$selectItem.filter(':enabled').prop('checked', checked);
  1288. this.updateRows(checked);
  1289. this.updateSelected();
  1290. this.trigger(checked ? 'check-all' : 'uncheck-all');
  1291. };
  1292. BootstrapTable.prototype.check = function (index) {
  1293. this.check_(true, index);
  1294. };
  1295. BootstrapTable.prototype.uncheck = function (index) {
  1296. this.check_(false, index);
  1297. };
  1298. BootstrapTable.prototype.check_ = function (checked, index) {
  1299. this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  1300. this.data[index][this.header.stateField] = checked;
  1301. this.updateSelected();
  1302. this.trigger(checked ? 'check' : 'uncheck', this.data[index]);
  1303. };
  1304. BootstrapTable.prototype.destroy = function () {
  1305. this.$el.insertBefore(this.$container);
  1306. $(this.options.toolbar).insertBefore(this.$el);
  1307. this.$container.next().remove();
  1308. this.$container.remove();
  1309. this.$el.html(this.$el_.html())
  1310. .css('margin-top', '0')
  1311. .attr('class', this.$el_.attr('class') || ''); // reset the class
  1312. };
  1313. BootstrapTable.prototype.showLoading = function () {
  1314. this.$loading.show();
  1315. };
  1316. BootstrapTable.prototype.hideLoading = function () {
  1317. this.$loading.hide();
  1318. };
  1319. BootstrapTable.prototype.togglePagination = function () {
  1320. this.options.pagination = !this.options.pagination;
  1321. var button = this.$toolbar.find('button[name="paginationSwitch"] i');
  1322. if (this.options.pagination) {
  1323. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown);
  1324. } else {
  1325. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp);
  1326. }
  1327. this.updatePagination();
  1328. };
  1329. BootstrapTable.prototype.refresh = function (params) {
  1330. if (params && params.url) {
  1331. this.options.url = params.url;
  1332. this.options.pageNumber = 1;
  1333. }
  1334. this.initServer(params && params.silent, params && params.query);
  1335. };
  1336. BootstrapTable.prototype.showColumn = function (field) {
  1337. this.toggleColumn(getFieldIndex(this.options.columns, field), true, true);
  1338. };
  1339. BootstrapTable.prototype.hideColumn = function (field) {
  1340. this.toggleColumn(getFieldIndex(this.options.columns, field), false, true);
  1341. };
  1342. BootstrapTable.prototype.filterBy = function (columns) {
  1343. this.filterColumns = $.isEmptyObject(columns) ? {}: columns;
  1344. this.options.pageNumber = 1;
  1345. this.initSearch();
  1346. this.updatePagination();
  1347. };
  1348. BootstrapTable.prototype.scrollTo = function (value) {
  1349. var $tbody = this.$container.find('.fixed-table-body');
  1350. if (typeof value === 'string') {
  1351. value = value === 'bottom' ? $tbody[0].scrollHeight : 0;
  1352. }
  1353. if (typeof value === 'number') {
  1354. $tbody.scrollTop(value);
  1355. }
  1356. };
  1357. BootstrapTable.prototype.selectPage = function (page) {
  1358. if (page > 0 && page <= this.options.totalPages) {
  1359. this.options.pageNumber = page;
  1360. this.updatePagination();
  1361. }
  1362. };
  1363. BootstrapTable.prototype.prevPage = function () {
  1364. if (this.options.pageNumber > 1) {
  1365. this.options.pageNumber--;
  1366. this.updatePagination();
  1367. }
  1368. };
  1369. BootstrapTable.prototype.nextPage = function () {
  1370. if (this.options.pageNumber < this.options.totalPages) {
  1371. this.options.pageNumber++;
  1372. this.updatePagination();
  1373. }
  1374. };
  1375. BootstrapTable.prototype.toggleView = function () {
  1376. this.options.cardView = !this.options.cardView;
  1377. this.initHeader();
  1378. this.initBody();
  1379. };
  1380. // BOOTSTRAP TABLE PLUGIN DEFINITION
  1381. // =======================
  1382. var allowedMethods = [
  1383. 'getOptions',
  1384. 'getSelections', 'getData',
  1385. 'load', 'append', 'prepend', 'remove',
  1386. 'insertRow', 'updateRow',
  1387. 'mergeCells',
  1388. 'checkAll', 'uncheckAll',
  1389. 'check', 'uncheck',
  1390. 'refresh',
  1391. 'resetView',
  1392. 'destroy',
  1393. 'showLoading', 'hideLoading',
  1394. 'showColumn', 'hideColumn',
  1395. 'filterBy',
  1396. 'scrollTo',
  1397. 'selectPage', 'prevPage', 'nextPage',
  1398. 'togglePagination',
  1399. 'toggleView'
  1400. ];
  1401. $.fn.bootstrapTable = function (option, _relatedTarget) {
  1402. var value;
  1403. this.each(function () {
  1404. var $this = $(this),
  1405. data = $this.data('bootstrap.table'),
  1406. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
  1407. typeof option === 'object' && option);
  1408. if (typeof option === 'string') {
  1409. if ($.inArray(option, allowedMethods) < 0) {
  1410. throw "Unknown method: " + option;
  1411. }
  1412. if (!data) {
  1413. return;
  1414. }
  1415. value = data[option](_relatedTarget);
  1416. if (option === 'destroy') {
  1417. $this.removeData('bootstrap.table');
  1418. }
  1419. }
  1420. if (!data) {
  1421. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  1422. }
  1423. });
  1424. return typeof value === 'undefined' ? this : value;
  1425. };
  1426. $.fn.bootstrapTable.Constructor = BootstrapTable;
  1427. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
  1428. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
  1429. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES;
  1430. $.fn.bootstrapTable.methods = allowedMethods;
  1431. // BOOTSTRAP TABLE INIT
  1432. // =======================
  1433. $(function () {
  1434. $('[data-toggle="table"]').bootstrapTable();
  1435. });
  1436. }(jQuery);