You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2691 lines
94 KiB

  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.9.1
  4. * https://github.com/wenzhixin/bootstrap-table/
  5. */
  6. !function ($) {
  7. 'use strict';
  8. // TOOLS DEFINITION
  9. // ======================
  10. var cachedWidth = null;
  11. // it only does '%s', and return '' when arguments are undefined
  12. var sprintf = function (str) {
  13. var args = arguments,
  14. flag = true,
  15. i = 1;
  16. str = str.replace(/%s/g, function () {
  17. var arg = args[i++];
  18. if (typeof arg === 'undefined') {
  19. flag = false;
  20. return '';
  21. }
  22. return arg;
  23. });
  24. return flag ? str : '';
  25. };
  26. var getPropertyFromOther = function (list, from, to, value) {
  27. var result = '';
  28. $.each(list, function (i, item) {
  29. if (item[from] === value) {
  30. result = item[to];
  31. return false;
  32. }
  33. return true;
  34. });
  35. return result;
  36. };
  37. var getFieldIndex = function (columns, field) {
  38. var index = -1;
  39. $.each(columns, function (i, column) {
  40. if (column.field === field) {
  41. index = i;
  42. return false;
  43. }
  44. return true;
  45. });
  46. return index;
  47. };
  48. // http://jsfiddle.net/wenyi/47nz7ez9/3/
  49. var setFieldIndex = function (columns) {
  50. var i, j, k,
  51. totalCol = 0,
  52. flag = [];
  53. for (i = 0; i < columns[0].length; i++) {
  54. totalCol += columns[0][i].colspan || 1;
  55. }
  56. for (i = 0; i < columns.length; i++) {
  57. flag[i] = [];
  58. for (j = 0; j < totalCol; j++) {
  59. flag[i][j] = false;
  60. }
  61. }
  62. for (i = 0; i < columns.length; i++) {
  63. for (j = 0; j < columns[i].length; j++) {
  64. var r = columns[i][j],
  65. rowspan = r.rowspan || 1,
  66. colspan = r.colspan || 1,
  67. index = $.inArray(false, flag[i]);
  68. if (colspan === 1) {
  69. r.fieldIndex = index;
  70. // when field is undefined, use index instead
  71. if (typeof r.field === 'undefined') {
  72. r.field = index;
  73. }
  74. }
  75. for (k = 0; k < rowspan; k++) {
  76. flag[i + k][index] = true;
  77. }
  78. for (k = 0; k < colspan; k++) {
  79. flag[i][index + k] = true;
  80. }
  81. }
  82. }
  83. };
  84. var getScrollBarWidth = function () {
  85. if (cachedWidth === null) {
  86. var inner = $('<p/>').addClass('fixed-table-scroll-inner'),
  87. outer = $('<div/>').addClass('fixed-table-scroll-outer'),
  88. w1, w2;
  89. outer.append(inner);
  90. $('body').append(outer);
  91. w1 = inner[0].offsetWidth;
  92. outer.css('overflow', 'scroll');
  93. w2 = inner[0].offsetWidth;
  94. if (w1 === w2) {
  95. w2 = outer[0].clientWidth;
  96. }
  97. outer.remove();
  98. cachedWidth = w1 - w2;
  99. }
  100. return cachedWidth;
  101. };
  102. var calculateObjectValue = function (self, name, args, defaultValue) {
  103. var func = name;
  104. if (typeof name === 'string') {
  105. // support obj.func1.func2
  106. var names = name.split('.');
  107. if (names.length > 1) {
  108. func = window;
  109. $.each(names, function (i, f) {
  110. func = func[f];
  111. });
  112. } else {
  113. func = window[name];
  114. }
  115. }
  116. if (typeof func === 'object') {
  117. return func;
  118. }
  119. if (typeof func === 'function') {
  120. return func.apply(self, args);
  121. }
  122. if (!func && typeof name === 'string' && sprintf.apply(this, [name].concat(args))) {
  123. return sprintf.apply(this, [name].concat(args));
  124. }
  125. return defaultValue;
  126. };
  127. var compareObjects = function (objectA, objectB, compareLength) {
  128. // Create arrays of property names
  129. var objectAProperties = Object.getOwnPropertyNames(objectA),
  130. objectBProperties = Object.getOwnPropertyNames(objectB),
  131. propName = '';
  132. if (compareLength) {
  133. // If number of properties is different, objects are not equivalent
  134. if (objectAProperties.length !== objectBProperties.length) {
  135. return false;
  136. }
  137. }
  138. for (var i = 0; i < objectAProperties.length; i++) {
  139. propName = objectAProperties[i];
  140. // If the property is not in the object B properties, continue with the next property
  141. if ($.inArray(propName, objectBProperties) > -1) {
  142. // If values of same property are not equal, objects are not equivalent
  143. if (objectA[propName] !== objectB[propName]) {
  144. return false;
  145. }
  146. }
  147. }
  148. // If we made it this far, objects are considered equivalent
  149. return true;
  150. };
  151. var escapeHTML = function (text) {
  152. if (typeof text === 'string') {
  153. return text
  154. .replace(/&/g, "&amp;")
  155. .replace(/</g, "&lt;")
  156. .replace(/>/g, "&gt;")
  157. .replace(/"/g, "&quot;")
  158. .replace(/'/g, "&#039;");
  159. }
  160. return text;
  161. };
  162. var getRealHeight = function ($el) {
  163. var height = 0;
  164. $el.children().each(function () {
  165. if (height < $(this).outerHeight(true)) {
  166. height = $(this).outerHeight(true);
  167. }
  168. });
  169. return height;
  170. };
  171. var getRealDataAttr = function (dataAttr) {
  172. for (var attr in dataAttr) {
  173. var auxAttr = attr.split(/(?=[A-Z])/).join('-').toLowerCase();
  174. if (auxAttr !== attr) {
  175. dataAttr[auxAttr] = dataAttr[attr];
  176. delete dataAttr[attr];
  177. }
  178. }
  179. return dataAttr;
  180. };
  181. var getItemField = function (item, field) {
  182. var value = item;
  183. if (typeof field !== 'string' || item.hasOwnProperty(field)) {
  184. return item[field];
  185. }
  186. var props = field.split('.');
  187. for (var p in props) {
  188. value = value[props[p]];
  189. }
  190. return value;
  191. };
  192. // BOOTSTRAP TABLE CLASS DEFINITION
  193. // ======================
  194. var BootstrapTable = function (el, options) {
  195. this.options = options;
  196. this.$el = $(el);
  197. this.$el_ = this.$el.clone();
  198. this.timeoutId_ = 0;
  199. this.timeoutFooter_ = 0;
  200. this.init();
  201. };
  202. BootstrapTable.DEFAULTS = {
  203. classes: 'table table-hover',
  204. locale: undefined,
  205. height: undefined,
  206. undefinedText: '-',
  207. sortName: undefined,
  208. sortOrder: 'asc',
  209. striped: false,
  210. columns: [[]],
  211. data: [],
  212. dataField: 'rows',
  213. method: 'get',
  214. url: undefined,
  215. ajax: undefined,
  216. cache: true,
  217. contentType: 'application/json',
  218. dataType: 'json',
  219. ajaxOptions: {},
  220. queryParams: function (params) {
  221. return params;
  222. },
  223. queryParamsType: 'limit', // undefined
  224. responseHandler: function (res) {
  225. return res;
  226. },
  227. pagination: false,
  228. onlyInfoPagination: false,
  229. sidePagination: 'client', // client or server
  230. totalRows: 0, // server side need to set
  231. pageNumber: 1,
  232. pageSize: 10,
  233. pageList: [10, 25, 50, 100],
  234. paginationHAlign: 'right', //right, left
  235. paginationVAlign: 'bottom', //bottom, top, both
  236. paginationDetailHAlign: 'left', //right, left
  237. paginationFirstText: '&laquo;',
  238. paginationPreText: '&lsaquo;',
  239. paginationNextText: '&rsaquo;',
  240. paginationLastText: '&raquo;',
  241. search: false,
  242. strictSearch: false,
  243. searchAlign: 'right',
  244. selectItemName: 'btSelectItem',
  245. showHeader: true,
  246. showFooter: false,
  247. showColumns: false,
  248. showPaginationSwitch: false,
  249. showRefresh: false,
  250. showToggle: false,
  251. buttonsAlign: 'right',
  252. smartDisplay: true,
  253. minimumCountColumns: 1,
  254. idField: undefined,
  255. uniqueId: undefined,
  256. cardView: false,
  257. detailView: false,
  258. detailFormatter: function (index, row) {
  259. return '';
  260. },
  261. trimOnSearch: true,
  262. clickToSelect: false,
  263. singleSelect: false,
  264. toolbar: undefined,
  265. toolbarAlign: 'left',
  266. checkboxHeader: true,
  267. sortable: true,
  268. silentSort: true,
  269. maintainSelected: false,
  270. searchTimeOut: 500,
  271. searchText: '',
  272. iconSize: undefined,
  273. iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome)
  274. icons: {
  275. paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
  276. paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
  277. refresh: 'glyphicon-refresh icon-refresh',
  278. toggle: 'glyphicon-list-alt icon-list-alt',
  279. columns: 'glyphicon-th icon-th',
  280. detailOpen: 'glyphicon-plus icon-plus',
  281. detailClose: 'glyphicon-minus icon-minus'
  282. },
  283. rowStyle: function (row, index) {
  284. return {};
  285. },
  286. rowAttributes: function (row, index) {
  287. return {};
  288. },
  289. onAll: function (name, args) {
  290. return false;
  291. },
  292. onClickCell: function (field, value, row, $element) {
  293. return false;
  294. },
  295. onDblClickCell: function (field, value, row, $element) {
  296. return false;
  297. },
  298. onClickRow: function (item, $element) {
  299. return false;
  300. },
  301. onDblClickRow: function (item, $element) {
  302. return false;
  303. },
  304. onSort: function (name, order) {
  305. return false;
  306. },
  307. onCheck: function (row) {
  308. return false;
  309. },
  310. onUncheck: function (row) {
  311. return false;
  312. },
  313. onCheckAll: function (rows) {
  314. return false;
  315. },
  316. onUncheckAll: function (rows) {
  317. return false;
  318. },
  319. onCheckSome: function (rows) {
  320. return false;
  321. },
  322. onUncheckSome: function (rows) {
  323. return false;
  324. },
  325. onLoadSuccess: function (data) {
  326. return false;
  327. },
  328. onLoadError: function (status) {
  329. return false;
  330. },
  331. onColumnSwitch: function (field, checked) {
  332. return false;
  333. },
  334. onPageChange: function (number, size) {
  335. return false;
  336. },
  337. onSearch: function (text) {
  338. return false;
  339. },
  340. onToggle: function (cardView) {
  341. return false;
  342. },
  343. onPreBody: function (data) {
  344. return false;
  345. },
  346. onPostBody: function () {
  347. return false;
  348. },
  349. onPostHeader: function () {
  350. return false;
  351. },
  352. onExpandRow: function (index, row, $detail) {
  353. return false;
  354. },
  355. onCollapseRow: function (index, row) {
  356. return false;
  357. },
  358. onRefreshOptions: function (options) {
  359. return false;
  360. },
  361. onResetView: function () {
  362. return false;
  363. }
  364. };
  365. BootstrapTable.LOCALES = [];
  366. BootstrapTable.LOCALES['en-US'] = BootstrapTable.LOCALES['en'] = {
  367. formatLoadingMessage: function () {
  368. return 'Loading, please wait...';
  369. },
  370. formatRecordsPerPage: function (pageNumber) {
  371. return sprintf('%s records per page', pageNumber);
  372. },
  373. formatShowingRows: function (pageFrom, pageTo, totalRows) {
  374. return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows);
  375. },
  376. formatDetailPagination: function (totalRows) {
  377. return sprintf('Showing %s rows', totalRows);
  378. },
  379. formatSearch: function () {
  380. return 'Search';
  381. },
  382. formatNoMatches: function () {
  383. return 'No matching records found';
  384. },
  385. formatPaginationSwitch: function () {
  386. return 'Hide/Show pagination';
  387. },
  388. formatRefresh: function () {
  389. return 'Refresh';
  390. },
  391. formatToggle: function () {
  392. return 'Toggle';
  393. },
  394. formatColumns: function () {
  395. return 'Columns';
  396. },
  397. formatAllRows: function () {
  398. return 'All';
  399. }
  400. };
  401. $.extend(BootstrapTable.DEFAULTS, BootstrapTable.LOCALES['en-US']);
  402. BootstrapTable.COLUMN_DEFAULTS = {
  403. radio: false,
  404. checkbox: false,
  405. checkboxEnabled: true,
  406. field: undefined,
  407. title: undefined,
  408. titleTooltip: undefined,
  409. 'class': undefined,
  410. align: undefined, // left, right, center
  411. halign: undefined, // left, right, center
  412. falign: undefined, // left, right, center
  413. valign: undefined, // top, middle, bottom
  414. width: undefined,
  415. sortable: false,
  416. order: 'asc', // asc, desc
  417. visible: true,
  418. switchable: true,
  419. clickToSelect: true,
  420. formatter: undefined,
  421. footerFormatter: undefined,
  422. events: undefined,
  423. sorter: undefined,
  424. sortName: undefined,
  425. cellStyle: undefined,
  426. searchable: true,
  427. searchFormatter: true,
  428. cardVisible: true
  429. };
  430. BootstrapTable.EVENTS = {
  431. 'all.bs.table': 'onAll',
  432. 'click-cell.bs.table': 'onClickCell',
  433. 'dbl-click-cell.bs.table': 'onDblClickCell',
  434. 'click-row.bs.table': 'onClickRow',
  435. 'dbl-click-row.bs.table': 'onDblClickRow',
  436. 'sort.bs.table': 'onSort',
  437. 'check.bs.table': 'onCheck',
  438. 'uncheck.bs.table': 'onUncheck',
  439. 'check-all.bs.table': 'onCheckAll',
  440. 'uncheck-all.bs.table': 'onUncheckAll',
  441. 'check-some.bs.table': 'onCheckSome',
  442. 'uncheck-some.bs.table': 'onUncheckSome',
  443. 'load-success.bs.table': 'onLoadSuccess',
  444. 'load-error.bs.table': 'onLoadError',
  445. 'column-switch.bs.table': 'onColumnSwitch',
  446. 'page-change.bs.table': 'onPageChange',
  447. 'search.bs.table': 'onSearch',
  448. 'toggle.bs.table': 'onToggle',
  449. 'pre-body.bs.table': 'onPreBody',
  450. 'post-body.bs.table': 'onPostBody',
  451. 'post-header.bs.table': 'onPostHeader',
  452. 'expand-row.bs.table': 'onExpandRow',
  453. 'collapse-row.bs.table': 'onCollapseRow',
  454. 'refresh-options.bs.table': 'onRefreshOptions',
  455. 'reset-view.bs.table': 'onResetView'
  456. };
  457. BootstrapTable.prototype.init = function () {
  458. this.initLocale();
  459. this.initContainer();
  460. this.initTable();
  461. this.initHeader();
  462. this.initData();
  463. this.initFooter();
  464. this.initToolbar();
  465. this.initPagination();
  466. this.initBody();
  467. this.initSearchText();
  468. this.initServer();
  469. };
  470. BootstrapTable.prototype.initLocale = function () {
  471. if (this.options.locale) {
  472. var parts = this.options.locale.split(/-|_/);
  473. parts[0].toLowerCase();
  474. parts[1] && parts[1].toUpperCase();
  475. if ($.fn.bootstrapTable.locales[this.options.locale]) {
  476. // locale as requested
  477. $.extend(this.options, $.fn.bootstrapTable.locales[this.options.locale]);
  478. } else if ($.fn.bootstrapTable.locales[parts.join('-')]) {
  479. // locale with sep set to - (in case original was specified with _)
  480. $.extend(this.options, $.fn.bootstrapTable.locales[parts.join('-')]);
  481. } else if ($.fn.bootstrapTable.locales[parts[0]]) {
  482. // short locale language code (i.e. 'en')
  483. $.extend(this.options, $.fn.bootstrapTable.locales[parts[0]]);
  484. }
  485. }
  486. };
  487. BootstrapTable.prototype.initContainer = function () {
  488. this.$container = $([
  489. '<div class="bootstrap-table">',
  490. '<div class="fixed-table-toolbar"></div>',
  491. this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
  492. '<div class="fixed-table-pagination" style="clear: both;"></div>' :
  493. '',
  494. '<div class="fixed-table-container">',
  495. '<div class="fixed-table-header"><table></table></div>',
  496. '<div class="fixed-table-body">',
  497. '<div class="fixed-table-loading">',
  498. this.options.formatLoadingMessage(),
  499. '</div>',
  500. '</div>',
  501. '<div class="fixed-table-footer"><table><tr></tr></table></div>',
  502. this.options.paginationVAlign === 'bottom' || this.options.paginationVAlign === 'both' ?
  503. '<div class="fixed-table-pagination"></div>' :
  504. '',
  505. '</div>',
  506. '</div>'
  507. ].join(''));
  508. this.$container.insertAfter(this.$el);
  509. this.$tableContainer = this.$container.find('.fixed-table-container');
  510. this.$tableHeader = this.$container.find('.fixed-table-header');
  511. this.$tableBody = this.$container.find('.fixed-table-body');
  512. this.$tableLoading = this.$container.find('.fixed-table-loading');
  513. this.$tableFooter = this.$container.find('.fixed-table-footer');
  514. this.$toolbar = this.$container.find('.fixed-table-toolbar');
  515. this.$pagination = this.$container.find('.fixed-table-pagination');
  516. this.$tableBody.append(this.$el);
  517. this.$container.after('<div class="clearfix"></div>');
  518. this.$el.addClass(this.options.classes);
  519. if (this.options.striped) {
  520. this.$el.addClass('table-striped');
  521. }
  522. if ($.inArray('table-no-bordered', this.options.classes.split(' ')) !== -1) {
  523. this.$tableContainer.addClass('table-no-bordered');
  524. }
  525. };
  526. BootstrapTable.prototype.initTable = function () {
  527. var that = this,
  528. columns = [],
  529. data = [];
  530. this.$header = this.$el.find('>thead');
  531. if (!this.$header.length) {
  532. this.$header = $('<thead></thead>').appendTo(this.$el);
  533. }
  534. this.$header.find('tr').each(function () {
  535. var column = [];
  536. $(this).find('th').each(function () {
  537. column.push($.extend({}, {
  538. title: $(this).html(),
  539. 'class': $(this).attr('class'),
  540. titleTooltip: $(this).attr('title'),
  541. rowspan: $(this).attr('rowspan') ? +$(this).attr('rowspan') : undefined,
  542. colspan: $(this).attr('colspan') ? +$(this).attr('colspan') : undefined
  543. }, $(this).data()));
  544. });
  545. columns.push(column);
  546. });
  547. if (!$.isArray(this.options.columns[0])) {
  548. this.options.columns = [this.options.columns];
  549. }
  550. this.options.columns = $.extend(true, [], columns, this.options.columns);
  551. this.columns = [];
  552. setFieldIndex(this.options.columns);
  553. $.each(this.options.columns, function (i, columns) {
  554. $.each(columns, function (j, column) {
  555. column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column);
  556. if (typeof column.fieldIndex !== 'undefined') {
  557. that.columns[column.fieldIndex] = column;
  558. }
  559. that.options.columns[i][j] = column;
  560. });
  561. });
  562. // if options.data is setting, do not process tbody data
  563. if (this.options.data.length) {
  564. return;
  565. }
  566. this.$el.find('>tbody>tr').each(function () {
  567. var row = {};
  568. // save tr's id, class and data-* attributes
  569. row._id = $(this).attr('id');
  570. row._class = $(this).attr('class');
  571. row._data = getRealDataAttr($(this).data());
  572. $(this).find('td').each(function (i) {
  573. var field = that.columns[i].field;
  574. row[field] = $(this).html();
  575. // save td's id, class and data-* attributes
  576. row['_' + field + '_id'] = $(this).attr('id');
  577. row['_' + field + '_class'] = $(this).attr('class');
  578. row['_' + field + '_rowspan'] = $(this).attr('rowspan');
  579. row['_' + field + '_title'] = $(this).attr('title');
  580. row['_' + field + '_data'] = getRealDataAttr($(this).data());
  581. });
  582. data.push(row);
  583. });
  584. this.options.data = data;
  585. };
  586. BootstrapTable.prototype.initHeader = function () {
  587. var that = this,
  588. visibleColumns = {},
  589. html = [];
  590. this.header = {
  591. fields: [],
  592. styles: [],
  593. classes: [],
  594. formatters: [],
  595. events: [],
  596. sorters: [],
  597. sortNames: [],
  598. cellStyles: [],
  599. searchables: []
  600. };
  601. $.each(this.options.columns, function (i, columns) {
  602. html.push('<tr>');
  603. if (i == 0 && !that.options.cardView && that.options.detailView) {
  604. html.push(sprintf('<th class="detail" rowspan="%s"><div class="fht-cell"></div></th>',
  605. that.options.columns.length));
  606. }
  607. $.each(columns, function (j, column) {
  608. var text = '',
  609. halign = '', // header align style
  610. align = '', // body align style
  611. style = '',
  612. class_ = sprintf(' class="%s"', column['class']),
  613. order = that.options.sortOrder || column.order,
  614. unitWidth = 'px',
  615. width = column.width;
  616. if (column.width !== undefined && (!that.options.cardView)) {
  617. if (typeof column.width === 'string') {
  618. if (column.width.indexOf('%') !== -1) {
  619. unitWidth = '%';
  620. }
  621. }
  622. }
  623. if (column.width && typeof column.width === 'string') {
  624. width = column.width.replace('%', '').replace('px', '');
  625. }
  626. halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align);
  627. align = sprintf('text-align: %s; ', column.align);
  628. style = sprintf('vertical-align: %s; ', column.valign);
  629. style += sprintf('width: %s; ', (column.checkbox || column.radio) && !width ?
  630. '36px' : (width ? width + unitWidth : undefined));
  631. if (typeof column.fieldIndex !== 'undefined') {
  632. that.header.fields[column.fieldIndex] = column.field;
  633. that.header.styles[column.fieldIndex] = align + style;
  634. that.header.classes[column.fieldIndex] = class_;
  635. that.header.formatters[column.fieldIndex] = column.formatter;
  636. that.header.events[column.fieldIndex] = column.events;
  637. that.header.sorters[column.fieldIndex] = column.sorter;
  638. that.header.sortNames[column.fieldIndex] = column.sortName;
  639. that.header.cellStyles[column.fieldIndex] = column.cellStyle;
  640. that.header.searchables[column.fieldIndex] = column.searchable;
  641. if (!column.visible) {
  642. return;
  643. }
  644. if (that.options.cardView && (!column.cardVisible)) {
  645. return;
  646. }
  647. visibleColumns[column.field] = column;
  648. }
  649. html.push('<th' + sprintf(' title="%s"', column.titleTooltip),
  650. column.checkbox || column.radio ?
  651. sprintf(' class="bs-checkbox %s"', column['class'] || '') :
  652. class_,
  653. sprintf(' style="%s"', halign + style),
  654. sprintf(' rowspan="%s"', column.rowspan),
  655. sprintf(' colspan="%s"', column.colspan),
  656. sprintf(' data-field="%s"', column.field),
  657. "tabindex='0'",
  658. '>');
  659. html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ?
  660. 'sortable both' : ''));
  661. text = column.title;
  662. if (column.checkbox) {
  663. if (!that.options.singleSelect && that.options.checkboxHeader) {
  664. text = '<label class="mt-checkbox mt-checkbox-single mt-checkbox-outline"><input name="btSelectAll" type="checkbox" /><span></span></label>';
  665. }
  666. that.header.stateField = column.field;
  667. }
  668. if (column.radio) {
  669. text = '';
  670. that.header.stateField = column.field;
  671. that.options.singleSelect = true;
  672. }
  673. html.push(text);
  674. html.push('</div>');
  675. html.push('<div class="fht-cell"></div>');
  676. html.push('</div>');
  677. html.push('</th>');
  678. });
  679. html.push('</tr>');
  680. });
  681. this.$header.html(html.join(''));
  682. this.$header.find('th[data-field]').each(function (i) {
  683. $(this).data(visibleColumns[$(this).data('field')]);
  684. });
  685. this.$container.off('click', '.th-inner').on('click', '.th-inner', function (event) {
  686. if (that.options.sortable && $(this).parent().data().sortable) {
  687. that.onSort(event);
  688. }
  689. });
  690. this.$header.children().children().off('keypress').on('keypress', function (event) {
  691. if (that.options.sortable && $(this).data().sortable) {
  692. var code = event.keyCode || event.which;
  693. if (code == 13) { //Enter keycode
  694. that.onSort(event);
  695. }
  696. }
  697. });
  698. if (!this.options.showHeader || this.options.cardView) {
  699. this.$header.hide();
  700. this.$tableHeader.hide();
  701. this.$tableLoading.css('top', 0);
  702. } else {
  703. this.$header.show();
  704. this.$tableHeader.show();
  705. this.$tableLoading.css('top', this.$header.outerHeight() + 1);
  706. // Assign the correct sortable arrow
  707. this.getCaret();
  708. }
  709. this.$selectAll = this.$header.find('[name="btSelectAll"]');
  710. this.$container.off('click', '[name="btSelectAll"]')
  711. .on('click', '[name="btSelectAll"]', function () {
  712. var checked = $(this).prop('checked');
  713. that[checked ? 'checkAll' : 'uncheckAll']();
  714. that.updateSelected();
  715. });
  716. };
  717. BootstrapTable.prototype.initFooter = function () {
  718. if (!this.options.showFooter || this.options.cardView) {
  719. this.$tableFooter.hide();
  720. } else {
  721. this.$tableFooter.show();
  722. }
  723. };
  724. /**
  725. * @param data
  726. * @param type: append / prepend
  727. */
  728. BootstrapTable.prototype.initData = function (data, type) {
  729. if (type === 'append') {
  730. this.data = this.data.concat(data);
  731. } else if (type === 'prepend') {
  732. this.data = [].concat(data).concat(this.data);
  733. } else {
  734. this.data = data || this.options.data;
  735. }
  736. // Fix #839 Records deleted when adding new row on filtered table
  737. if (type === 'append') {
  738. this.options.data = this.options.data.concat(data);
  739. } else if (type === 'prepend') {
  740. this.options.data = [].concat(data).concat(this.options.data);
  741. } else {
  742. this.options.data = this.data;
  743. }
  744. if (this.options.sidePagination === 'server') {
  745. return;
  746. }
  747. this.initSort();
  748. };
  749. BootstrapTable.prototype.initSort = function () {
  750. var that = this,
  751. name = this.options.sortName,
  752. order = this.options.sortOrder === 'desc' ? -1 : 1,
  753. index = $.inArray(this.options.sortName, this.header.fields);
  754. if (index !== -1) {
  755. this.data.sort(function (a, b) {
  756. if (that.header.sortNames[index]) {
  757. name = that.header.sortNames[index];
  758. }
  759. var aa = getItemField(a, name),
  760. bb = getItemField(b, name),
  761. value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]);
  762. if (value !== undefined) {
  763. return order * value;
  764. }
  765. // Fix #161: undefined or null string sort bug.
  766. if (aa === undefined || aa === null) {
  767. aa = '';
  768. }
  769. if (bb === undefined || bb === null) {
  770. bb = '';
  771. }
  772. // IF both values are numeric, do a numeric comparison
  773. if ($.isNumeric(aa) && $.isNumeric(bb)) {
  774. // Convert numerical values form string to float.
  775. aa = parseFloat(aa);
  776. bb = parseFloat(bb);
  777. if (aa < bb) {
  778. return order * -1;
  779. }
  780. return order;
  781. }
  782. if (aa === bb) {
  783. return 0;
  784. }
  785. // If value is not a string, convert to string
  786. if (typeof aa !== 'string') {
  787. aa = aa.toString();
  788. }
  789. if (aa.localeCompare(bb) === -1) {
  790. return order * -1;
  791. }
  792. return order;
  793. });
  794. }
  795. };
  796. BootstrapTable.prototype.onSort = function (event) {
  797. var $this = event.type === "keypress" ? $(event.currentTarget) : $(event.currentTarget).parent(),
  798. $this_ = this.$header.find('th').eq($this.index());
  799. this.$header.add(this.$header_).find('span.order').remove();
  800. if (this.options.sortName === $this.data('field')) {
  801. this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc';
  802. } else {
  803. this.options.sortName = $this.data('field');
  804. this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
  805. }
  806. this.trigger('sort', this.options.sortName, this.options.sortOrder);
  807. $this.add($this_).data('order', this.options.sortOrder);
  808. // Assign the correct sortable arrow
  809. this.getCaret();
  810. if (this.options.sidePagination === 'server') {
  811. this.initServer(this.options.silentSort);
  812. return;
  813. }
  814. this.initSort();
  815. this.initBody();
  816. };
  817. BootstrapTable.prototype.initToolbar = function () {
  818. var that = this,
  819. html = [],
  820. timeoutId = 0,
  821. $keepOpen,
  822. $search,
  823. switchableCount = 0;
  824. this.$toolbar.html('');
  825. if (typeof this.options.toolbar === 'string' || typeof this.options.toolbar === 'object') {
  826. $(sprintf('<div class="bars pull-%s"></div>', this.options.toolbarAlign))
  827. .appendTo(this.$toolbar)
  828. .append($(this.options.toolbar));
  829. }
  830. // showColumns, showToggle, showRefresh
  831. html = [sprintf('<div class="columns columns-%s btn-group pull-%s">',
  832. this.options.buttonsAlign, this.options.buttonsAlign)];
  833. if (typeof this.options.icons === 'string') {
  834. this.options.icons = calculateObjectValue(null, this.options.icons);
  835. }
  836. if (this.options.showPaginationSwitch) {
  837. html.push(sprintf('<button class="btn btn-default" type="button" name="paginationSwitch" title="%s">',
  838. this.options.formatPaginationSwitch()),
  839. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown),
  840. '</button>');
  841. }
  842. if (this.options.showRefresh) {
  843. html.push(sprintf('<button class="btn btn-default' +
  844. sprintf(' btn-%s', this.options.iconSize) +
  845. '" type="button" name="refresh" title="%s">',
  846. this.options.formatRefresh()),
  847. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh),
  848. '</button>');
  849. }
  850. if (this.options.showToggle) {
  851. html.push(sprintf('<button class="btn btn-default' +
  852. sprintf(' btn-%s', this.options.iconSize) +
  853. '" type="button" name="toggle" title="%s">',
  854. this.options.formatToggle()),
  855. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggle),
  856. '</button>');
  857. }
  858. if (this.options.showColumns) {
  859. html.push(sprintf('<div class="keep-open btn-group" title="%s">',
  860. this.options.formatColumns()),
  861. '<button type="button" class="btn btn-default' +
  862. sprintf(' btn-%s', this.options.iconSize) +
  863. ' dropdown-toggle" data-toggle="dropdown">',
  864. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns),
  865. ' <span class="caret"></span>',
  866. '</button>',
  867. '<ul class="dropdown-menu" role="menu">');
  868. $.each(this.columns, function (i, column) {
  869. if (column.radio || column.checkbox) {
  870. return;
  871. }
  872. if (that.options.cardView && (!column.cardVisible)) {
  873. return;
  874. }
  875. var checked = column.visible ? ' checked="checked"' : '';
  876. if (column.switchable) {
  877. html.push(sprintf('<li>' +
  878. '<label class="mt-checkbox mt-checkbox-outline"><input type="checkbox" data-field="%s" value="%s"%s> %s' +
  879. '<span></span></label></li>', column.field, i, checked, column.title));
  880. switchableCount++;
  881. }
  882. });
  883. html.push('</ul>',
  884. '</div>');
  885. }
  886. html.push('</div>');
  887. // Fix #188: this.showToolbar is for extentions
  888. if (this.showToolbar || html.length > 2) {
  889. this.$toolbar.append(html.join(''));
  890. }
  891. if (this.options.showPaginationSwitch) {
  892. this.$toolbar.find('button[name="paginationSwitch"]')
  893. .off('click').on('click', $.proxy(this.togglePagination, this));
  894. }
  895. if (this.options.showRefresh) {
  896. this.$toolbar.find('button[name="refresh"]')
  897. .off('click').on('click', $.proxy(this.refresh, this));
  898. }
  899. if (this.options.showToggle) {
  900. this.$toolbar.find('button[name="toggle"]')
  901. .off('click').on('click', function () {
  902. that.toggleView();
  903. });
  904. }
  905. if (this.options.showColumns) {
  906. $keepOpen = this.$toolbar.find('.keep-open');
  907. if (switchableCount <= this.options.minimumCountColumns) {
  908. $keepOpen.find('input').prop('disabled', true);
  909. }
  910. $keepOpen.find('li').off('click').on('click', function (event) {
  911. event.stopImmediatePropagation();
  912. });
  913. $keepOpen.find('input').off('click').on('click', function () {
  914. var $this = $(this);
  915. that.toggleColumn(getFieldIndex(that.columns,
  916. $(this).data('field')), $this.prop('checked'), false);
  917. that.trigger('column-switch', $(this).data('field'), $this.prop('checked'));
  918. });
  919. }
  920. if (this.options.search) {
  921. html = [];
  922. html.push(
  923. '<div class="pull-' + this.options.searchAlign + ' search">',
  924. sprintf('<input class="form-control' +
  925. sprintf(' input-%s', this.options.iconSize) +
  926. '" type="text" placeholder="%s">',
  927. this.options.formatSearch()),
  928. '</div>');
  929. this.$toolbar.append(html.join(''));
  930. $search = this.$toolbar.find('.search input');
  931. $search.off('keyup drop').on('keyup drop', function (event) {
  932. clearTimeout(timeoutId); // doesn't matter if it's 0
  933. timeoutId = setTimeout(function () {
  934. that.onSearch(event);
  935. }, that.options.searchTimeOut);
  936. });
  937. }
  938. };
  939. BootstrapTable.prototype.onSearch = function (event) {
  940. var text = $.trim($(event.currentTarget).val());
  941. // trim search input
  942. if (this.options.trimOnSearch && $(event.currentTarget).val() !== text) {
  943. $(event.currentTarget).val(text);
  944. }
  945. if (text === this.searchText) {
  946. return;
  947. }
  948. this.searchText = text;
  949. this.options.pageNumber = 1;
  950. this.initSearch();
  951. this.updatePagination();
  952. this.trigger('search', text);
  953. };
  954. BootstrapTable.prototype.initSearch = function () {
  955. var that = this;
  956. if (this.options.sidePagination !== 'server') {
  957. var s = this.searchText && this.searchText.toLowerCase();
  958. var f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns;
  959. // Check filter
  960. this.data = f ? $.grep(this.options.data, function (item, i) {
  961. for (var key in f) {
  962. if ($.isArray(f[key])) {
  963. if ($.inArray(item[key], f[key]) === -1) {
  964. return false;
  965. }
  966. } else if (item[key] !== f[key]) {
  967. return false;
  968. }
  969. }
  970. return true;
  971. }) : this.options.data;
  972. this.data = s ? $.grep(this.data, function (item, i) {
  973. for (var key in item) {
  974. key = $.isNumeric(key) ? parseInt(key, 10) : key;
  975. var value = item[key],
  976. column = that.columns[getFieldIndex(that.columns, key)],
  977. j = $.inArray(key, that.header.fields);
  978. // Fix #142: search use formated data
  979. if (column && column.searchFormatter) {
  980. value = calculateObjectValue(column,
  981. that.header.formatters[j], [value, item, i], value);
  982. }
  983. var index = $.inArray(key, that.header.fields);
  984. if (index !== -1 && that.header.searchables[index] && (typeof value === 'string' || typeof value === 'number')) {
  985. if (that.options.strictSearch) {
  986. if ((value + '').toLowerCase() === s) {
  987. return true;
  988. }
  989. } else {
  990. if ((value + '').toLowerCase().indexOf(s) !== -1) {
  991. return true;
  992. }
  993. }
  994. }
  995. }
  996. return false;
  997. }) : this.data;
  998. }
  999. };
  1000. BootstrapTable.prototype.initPagination = function () {
  1001. if (!this.options.pagination) {
  1002. this.$pagination.hide();
  1003. return;
  1004. } else {
  1005. this.$pagination.show();
  1006. }
  1007. var that = this,
  1008. html = [],
  1009. $allSelected = false,
  1010. i, from, to,
  1011. $pageList,
  1012. $first, $pre,
  1013. $next, $last,
  1014. $number,
  1015. data = this.getData();
  1016. if (this.options.sidePagination !== 'server') {
  1017. this.options.totalRows = data.length;
  1018. }
  1019. this.totalPages = 0;
  1020. if (this.options.totalRows) {
  1021. if (this.options.pageSize === this.options.formatAllRows()) {
  1022. this.options.pageSize = this.options.totalRows;
  1023. $allSelected = true;
  1024. } else if (this.options.pageSize === this.options.totalRows) {
  1025. // Fix #667 Table with pagination,
  1026. // multiple pages and a search that matches to one page throws exception
  1027. var pageLst = typeof this.options.pageList === 'string' ?
  1028. this.options.pageList.replace('[', '').replace(']', '')
  1029. .replace(/ /g, '').toLowerCase().split(',') : this.options.pageList;
  1030. if ($.inArray(this.options.formatAllRows().toLowerCase(), pageLst) > -1) {
  1031. $allSelected = true;
  1032. }
  1033. }
  1034. this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
  1035. this.options.totalPages = this.totalPages;
  1036. }
  1037. if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
  1038. this.options.pageNumber = this.totalPages;
  1039. }
  1040. this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
  1041. this.pageTo = this.options.pageNumber * this.options.pageSize;
  1042. if (this.pageTo > this.options.totalRows) {
  1043. this.pageTo = this.options.totalRows;
  1044. }
  1045. html.push(
  1046. '<div class="pull-' + this.options.paginationDetailHAlign + ' pagination-detail">',
  1047. '<span class="pagination-info">',
  1048. this.options.onlyInfoPagination ? this.options.formatDetailPagination(this.options.totalRows) :
  1049. this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
  1050. '</span>');
  1051. if (!this.options.onlyInfoPagination) {
  1052. html.push('<span class="page-list">');
  1053. var pageNumber = [
  1054. sprintf('<span class="btn-group %s">',
  1055. this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
  1056. 'dropdown' : 'dropup'),
  1057. '<button type="button" class="btn btn-default ' +
  1058. sprintf(' btn-%s', this.options.iconSize) +
  1059. ' dropdown-toggle" data-toggle="dropdown">',
  1060. '<span class="page-size">',
  1061. $allSelected ? this.options.formatAllRows() : this.options.pageSize,
  1062. '</span>',
  1063. ' <span class="caret"></span>',
  1064. '</button>',
  1065. '<ul class="dropdown-menu" role="menu">'
  1066. ],
  1067. pageList = this.options.pageList;
  1068. if (typeof this.options.pageList === 'string') {
  1069. var list = this.options.pageList.replace('[', '').replace(']', '')
  1070. .replace(/ /g, '').split(',');
  1071. pageList = [];
  1072. $.each(list, function (i, value) {
  1073. pageList.push(value.toUpperCase() === that.options.formatAllRows().toUpperCase() ?
  1074. that.options.formatAllRows() : +value);
  1075. });
  1076. }
  1077. $.each(pageList, function (i, page) {
  1078. if (!that.options.smartDisplay || i === 0 || pageList[i - 1] <= that.options.totalRows) {
  1079. var active;
  1080. if ($allSelected) {
  1081. active = page === that.options.formatAllRows() ? ' class="active"' : '';
  1082. } else {
  1083. active = page === that.options.pageSize ? ' class="active"' : '';
  1084. }
  1085. pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page));
  1086. }
  1087. });
  1088. pageNumber.push('</ul></span>');
  1089. html.push(this.options.formatRecordsPerPage(pageNumber.join('')));
  1090. html.push('</span>');
  1091. html.push('</div>',
  1092. '<div class="pull-' + this.options.paginationHAlign + ' pagination">',
  1093. '<ul class="pagination' + sprintf(' pagination-%s', this.options.iconSize) + '">',
  1094. '<li class="page-first"><a href="javascript:void(0)">' + this.options.paginationFirstText + '</a></li>',
  1095. '<li class="page-pre"><a href="javascript:void(0)">' + this.options.paginationPreText + '</a></li>');
  1096. if (this.totalPages < 5) {
  1097. from = 1;
  1098. to = this.totalPages;
  1099. } else {
  1100. from = this.options.pageNumber - 2;
  1101. to = from + 4;
  1102. if (from < 1) {
  1103. from = 1;
  1104. to = 5;
  1105. }
  1106. if (to > this.totalPages) {
  1107. to = this.totalPages;
  1108. from = to - 4;
  1109. }
  1110. }
  1111. for (i = from; i <= to; i++) {
  1112. html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
  1113. '<a href="javascript:void(0)">', i, '</a>',
  1114. '</li>');
  1115. }
  1116. html.push(
  1117. '<li class="page-next"><a href="javascript:void(0)">' + this.options.paginationNextText + '</a></li>',
  1118. '<li class="page-last"><a href="javascript:void(0)">' + this.options.paginationLastText + '</a></li>',
  1119. '</ul>',
  1120. '</div>');
  1121. }
  1122. this.$pagination.html(html.join(''));
  1123. if (!this.options.onlyInfoPagination) {
  1124. $pageList = this.$pagination.find('.page-list a');
  1125. $first = this.$pagination.find('.page-first');
  1126. $pre = this.$pagination.find('.page-pre');
  1127. $next = this.$pagination.find('.page-next');
  1128. $last = this.$pagination.find('.page-last');
  1129. $number = this.$pagination.find('.page-number');
  1130. if (this.options.pageNumber <= 1) {
  1131. $first.addClass('disabled');
  1132. $pre.addClass('disabled');
  1133. }
  1134. if (this.options.pageNumber >= this.totalPages) {
  1135. $next.addClass('disabled');
  1136. $last.addClass('disabled');
  1137. }
  1138. if (this.options.smartDisplay) {
  1139. if (this.totalPages <= 1) {
  1140. this.$pagination.find('div.pagination').hide();
  1141. }
  1142. if (pageList.length < 2 || this.options.totalRows <= pageList[0]) {
  1143. this.$pagination.find('span.page-list').hide();
  1144. }
  1145. // when data is empty, hide the pagination
  1146. this.$pagination[this.getData().length ? 'show' : 'hide']();
  1147. }
  1148. if ($allSelected) {
  1149. this.options.pageSize = this.options.formatAllRows();
  1150. }
  1151. $pageList.off('click').on('click', $.proxy(this.onPageListChange, this));
  1152. $first.off('click').on('click', $.proxy(this.onPageFirst, this));
  1153. $pre.off('click').on('click', $.proxy(this.onPagePre, this));
  1154. $next.off('click').on('click', $.proxy(this.onPageNext, this));
  1155. $last.off('click').on('click', $.proxy(this.onPageLast, this));
  1156. $number.off('click').on('click', $.proxy(this.onPageNumber, this));
  1157. }
  1158. };
  1159. BootstrapTable.prototype.updatePagination = function (event) {
  1160. // Fix #171: IE disabled button can be clicked bug.
  1161. if (event && $(event.currentTarget).hasClass('disabled')) {
  1162. return;
  1163. }
  1164. if (!this.options.maintainSelected) {
  1165. this.resetRows();
  1166. }
  1167. this.initPagination();
  1168. if (this.options.sidePagination === 'server') {
  1169. this.initServer();
  1170. } else {
  1171. this.initBody();
  1172. }
  1173. this.trigger('page-change', this.options.pageNumber, this.options.pageSize);
  1174. };
  1175. BootstrapTable.prototype.onPageListChange = function (event) {
  1176. var $this = $(event.currentTarget);
  1177. $this.parent().addClass('active').siblings().removeClass('active');
  1178. this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ?
  1179. this.options.formatAllRows() : +$this.text();
  1180. this.$toolbar.find('.page-size').text(this.options.pageSize);
  1181. this.updatePagination(event);
  1182. };
  1183. BootstrapTable.prototype.onPageFirst = function (event) {
  1184. this.options.pageNumber = 1;
  1185. this.updatePagination(event);
  1186. };
  1187. BootstrapTable.prototype.onPagePre = function (event) {
  1188. this.options.pageNumber--;
  1189. this.updatePagination(event);
  1190. };
  1191. BootstrapTable.prototype.onPageNext = function (event) {
  1192. this.options.pageNumber++;
  1193. this.updatePagination(event);
  1194. };
  1195. BootstrapTable.prototype.onPageLast = function (event) {
  1196. this.options.pageNumber = this.totalPages;
  1197. this.updatePagination(event);
  1198. };
  1199. BootstrapTable.prototype.onPageNumber = function (event) {
  1200. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  1201. return;
  1202. }
  1203. this.options.pageNumber = +$(event.currentTarget).text();
  1204. this.updatePagination(event);
  1205. };
  1206. BootstrapTable.prototype.initBody = function (fixedScroll) {
  1207. var that = this,
  1208. html = [],
  1209. data = this.getData();
  1210. this.trigger('pre-body', data);
  1211. this.$body = this.$el.find('>tbody');
  1212. if (!this.$body.length) {
  1213. this.$body = $('<tbody></tbody>').appendTo(this.$el);
  1214. }
  1215. //Fix #389 Bootstrap-table-flatJSON is not working
  1216. if (!this.options.pagination || this.options.sidePagination === 'server') {
  1217. this.pageFrom = 1;
  1218. this.pageTo = data.length;
  1219. }
  1220. for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
  1221. var key,
  1222. item = data[i],
  1223. style = {},
  1224. csses = [],
  1225. data_ = '',
  1226. attributes = {},
  1227. htmlAttributes = [];
  1228. style = calculateObjectValue(this.options, this.options.rowStyle, [item, i], style);
  1229. if (style && style.css) {
  1230. for (key in style.css) {
  1231. csses.push(key + ': ' + style.css[key]);
  1232. }
  1233. }
  1234. attributes = calculateObjectValue(this.options,
  1235. this.options.rowAttributes, [item, i], attributes);
  1236. if (attributes) {
  1237. for (key in attributes) {
  1238. htmlAttributes.push(sprintf('%s="%s"', key, escapeHTML(attributes[key])));
  1239. }
  1240. }
  1241. if (item._data && !$.isEmptyObject(item._data)) {
  1242. $.each(item._data, function (k, v) {
  1243. // ignore data-index
  1244. if (k === 'index') {
  1245. return;
  1246. }
  1247. data_ += sprintf(' data-%s="%s"', k, v);
  1248. });
  1249. }
  1250. html.push('<tr',
  1251. sprintf(' %s', htmlAttributes.join(' ')),
  1252. sprintf(' id="%s"', $.isArray(item) ? undefined : item._id),
  1253. sprintf(' class="%s"', style.classes || ($.isArray(item) ? undefined : item._class)),
  1254. sprintf(' data-index="%s"', i),
  1255. sprintf(' data-uniqueid="%s"', item[this.options.uniqueId]),
  1256. sprintf('%s', data_),
  1257. '>'
  1258. );
  1259. if (this.options.cardView) {
  1260. html.push(sprintf('<td colspan="%s">', this.header.fields.length));
  1261. }
  1262. if (!this.options.cardView && this.options.detailView) {
  1263. html.push('<td>',
  1264. '<a class="detail-icon" href="javascript:">',
  1265. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.detailOpen),
  1266. '</a>',
  1267. '</td>');
  1268. }
  1269. $.each(this.header.fields, function (j, field) {
  1270. var text = '',
  1271. value = getItemField(item, field),
  1272. type = '',
  1273. cellStyle = {},
  1274. id_ = '',
  1275. class_ = that.header.classes[j],
  1276. data_ = '',
  1277. rowspan_ = '',
  1278. title_ = '',
  1279. column = that.columns[getFieldIndex(that.columns, field)];
  1280. if (!column.visible) {
  1281. return;
  1282. }
  1283. style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
  1284. value = calculateObjectValue(column,
  1285. that.header.formatters[j], [value, item, i], value);
  1286. // handle td's id and class
  1287. if (item['_' + field + '_id']) {
  1288. id_ = sprintf(' id="%s"', item['_' + field + '_id']);
  1289. }
  1290. if (item['_' + field + '_class']) {
  1291. class_ = sprintf(' class="%s"', item['_' + field + '_class']);
  1292. }
  1293. if (item['_' + field + '_rowspan']) {
  1294. rowspan_ = sprintf(' rowspan="%s"', item['_' + field + '_rowspan']);
  1295. }
  1296. if (item['_' + field + '_title']) {
  1297. title_ = sprintf(' title="%s"', item['_' + field + '_title']);
  1298. }
  1299. cellStyle = calculateObjectValue(that.header,
  1300. that.header.cellStyles[j], [value, item, i], cellStyle);
  1301. if (cellStyle.classes) {
  1302. class_ = sprintf(' class="%s"', cellStyle.classes);
  1303. }
  1304. if (cellStyle.css) {
  1305. var csses_ = [];
  1306. for (var key in cellStyle.css) {
  1307. csses_.push(key + ': ' + cellStyle.css[key]);
  1308. }
  1309. style = sprintf('style="%s"', csses_.concat(that.header.styles[j]).join('; '));
  1310. }
  1311. if (item['_' + field + '_data'] && !$.isEmptyObject(item['_' + field + '_data'])) {
  1312. $.each(item['_' + field + '_data'], function (k, v) {
  1313. // ignore data-index
  1314. if (k === 'index') {
  1315. return;
  1316. }
  1317. data_ += sprintf(' data-%s="%s"', k, v);
  1318. });
  1319. }
  1320. if (column.checkbox || column.radio) {
  1321. type = column.checkbox ? 'checkbox' : type;
  1322. type = column.radio ? 'radio' : type;
  1323. text = [that.options.cardView ?
  1324. '<div class="card-view">' : '<td class="bs-checkbox">',
  1325. '<label class="' + (type == 'checkbox' ? 'mt-checkbox mt-checkbox-single mt-checkbox-outline' : 'mt-radio mt-radio-single mt-radio-outline') + '"><input' +
  1326. sprintf(' data-index="%s"', i) +
  1327. sprintf(' name="%s"', that.options.selectItemName) +
  1328. sprintf(' type="%s"', type) +
  1329. sprintf(' value="%s"', item[that.options.idField]) +
  1330. sprintf(' checked="%s"', value === true ||
  1331. (value && value.checked) ? 'checked' : undefined) +
  1332. sprintf(' disabled="%s"', !column.checkboxEnabled ||
  1333. (value && value.disabled) ? 'disabled' : undefined) +
  1334. ' /><span></span></label>',
  1335. that.header.formatters[j] && typeof value === 'string' ? value : '',
  1336. that.options.cardView ? '</div>' : '</td>'
  1337. ].join('');
  1338. item[that.header.stateField] = value === true || (value && value.checked);
  1339. } else {
  1340. value = typeof value === 'undefined' || value === null ?
  1341. that.options.undefinedText : value;
  1342. text = that.options.cardView ? ['<div class="card-view">',
  1343. that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style,
  1344. getPropertyFromOther(that.columns, 'field', 'title', field)) : '',
  1345. sprintf('<span class="value">%s</span>', value),
  1346. '</div>'
  1347. ].join('') : [sprintf('<td%s %s %s %s %s %s>', id_, class_, style, data_, rowspan_, title_),
  1348. value,
  1349. '</td>'
  1350. ].join('');
  1351. // Hide empty data on Card view when smartDisplay is set to true.
  1352. if (that.options.cardView && that.options.smartDisplay && value === '') {
  1353. // Should set a placeholder for event binding correct fieldIndex
  1354. text = '<div class="card-view"></div>';
  1355. }
  1356. }
  1357. html.push(text);
  1358. });
  1359. if (this.options.cardView) {
  1360. html.push('</td>');
  1361. }
  1362. html.push('</tr>');
  1363. }
  1364. // show no records
  1365. if (!html.length) {
  1366. html.push('<tr class="no-records-found">',
  1367. sprintf('<td colspan="%s">%s</td>',
  1368. this.$header.find('th').length, this.options.formatNoMatches()),
  1369. '</tr>');
  1370. }
  1371. this.$body.html(html.join(''));
  1372. if (!fixedScroll) {
  1373. this.scrollTo(0);
  1374. }
  1375. // click to select by column
  1376. this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', function (e) {
  1377. var $td = $(this),
  1378. $tr = $td.parent(),
  1379. item = that.data[$tr.data('index')],
  1380. index = $td[0].cellIndex,
  1381. field = that.header.fields[that.options.detailView && !that.options.cardView ? index - 1 : index],
  1382. column = that.columns[getFieldIndex(that.columns, field)],
  1383. value = getItemField(item, field);
  1384. if ($td.find('.detail-icon').length) {
  1385. return;
  1386. }
  1387. that.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td);
  1388. that.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr);
  1389. // if click to select - then trigger the checkbox/radio click
  1390. if (e.type === 'click' && that.options.clickToSelect && column.clickToSelect) {
  1391. var $selectItem = $tr.find(sprintf('[name="%s"]', that.options.selectItemName));
  1392. if ($selectItem.length) {
  1393. $selectItem[0].click(); // #144: .trigger('click') bug
  1394. }
  1395. }
  1396. });
  1397. this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', function () {
  1398. var $this = $(this),
  1399. $tr = $this.parent().parent(),
  1400. index = $tr.data('index'),
  1401. row = data[index]; // Fix #980 Detail view, when searching, returns wrong row
  1402. // remove and update
  1403. if ($tr.next().is('tr.detail-view')) {
  1404. $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailOpen));
  1405. $tr.next().remove();
  1406. that.trigger('collapse-row', index, row);
  1407. } else {
  1408. $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailClose));
  1409. $tr.after(sprintf('<tr class="detail-view"><td colspan="%s">%s</td></tr>',
  1410. $tr.find('td').length, calculateObjectValue(that.options,
  1411. that.options.detailFormatter, [index, row], '')));
  1412. that.trigger('expand-row', index, row, $tr.next().find('td'));
  1413. }
  1414. that.resetView();
  1415. });
  1416. this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
  1417. this.$selectItem.off('click').on('click', function (event) {
  1418. event.stopImmediatePropagation();
  1419. var $this = $(this),
  1420. checked = $this.prop('checked'),
  1421. row = that.data[$this.data('index')];
  1422. if (that.options.maintainSelected && $(this).is(':radio')) {
  1423. $.each(that.options.data, function (i, row) {
  1424. row[that.header.stateField] = false;
  1425. });
  1426. }
  1427. row[that.header.stateField] = checked;
  1428. if (that.options.singleSelect) {
  1429. that.$selectItem.not(this).each(function () {
  1430. that.data[$(this).data('index')][that.header.stateField] = false;
  1431. });
  1432. that.$selectItem.filter(':checked').not(this).prop('checked', false);
  1433. }
  1434. that.updateSelected();
  1435. that.trigger(checked ? 'check' : 'uncheck', row, $this);
  1436. });
  1437. $.each(this.header.events, function (i, events) {
  1438. if (!events) {
  1439. return;
  1440. }
  1441. // fix bug, if events is defined with namespace
  1442. if (typeof events === 'string') {
  1443. events = calculateObjectValue(null, events);
  1444. }
  1445. var field = that.header.fields[i],
  1446. fieldIndex = $.inArray(field, that.getVisibleFields());
  1447. if (that.options.detailView && !that.options.cardView) {
  1448. fieldIndex += 1;
  1449. }
  1450. for (var key in events) {
  1451. that.$body.find('>tr:not(.no-records-found)').each(function () {
  1452. var $tr = $(this),
  1453. $td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(fieldIndex),
  1454. index = key.indexOf(' '),
  1455. name = key.substring(0, index),
  1456. el = key.substring(index + 1),
  1457. func = events[key];
  1458. $td.find(el).off(name).on(name, function (e) {
  1459. var index = $tr.data('index'),
  1460. row = that.data[index],
  1461. value = row[field];
  1462. func.apply(this, [e, value, row, index]);
  1463. });
  1464. });
  1465. }
  1466. });
  1467. this.updateSelected();
  1468. this.resetView();
  1469. this.trigger('post-body');
  1470. };
  1471. BootstrapTable.prototype.initServer = function (silent, query) {
  1472. var that = this,
  1473. data = {},
  1474. params = {
  1475. pageSize: this.options.pageSize === this.options.formatAllRows() ?
  1476. this.options.totalRows : this.options.pageSize,
  1477. pageNumber: this.options.pageNumber,
  1478. searchText: this.searchText,
  1479. sortName: this.options.sortName,
  1480. sortOrder: this.options.sortOrder
  1481. },
  1482. request;
  1483. if (!this.options.url && !this.options.ajax) {
  1484. return;
  1485. }
  1486. if (this.options.queryParamsType === 'limit') {
  1487. params = {
  1488. search: params.searchText,
  1489. sort: params.sortName,
  1490. order: params.sortOrder
  1491. };
  1492. if (this.options.pagination) {
  1493. params.limit = this.options.pageSize === this.options.formatAllRows() ?
  1494. this.options.totalRows : this.options.pageSize;
  1495. params.offset = this.options.pageSize === this.options.formatAllRows() ?
  1496. 0 : this.options.pageSize * (this.options.pageNumber - 1);
  1497. }
  1498. }
  1499. if (!($.isEmptyObject(this.filterColumnsPartial))) {
  1500. params['filter'] = JSON.stringify(this.filterColumnsPartial, null);
  1501. }
  1502. data = calculateObjectValue(this.options, this.options.queryParams, [params], data);
  1503. $.extend(data, query || {});
  1504. // false to stop request
  1505. if (data === false) {
  1506. return;
  1507. }
  1508. if (!silent) {
  1509. this.$tableLoading.show();
  1510. }
  1511. request = $.extend({}, calculateObjectValue(null, this.options.ajaxOptions), {
  1512. type: this.options.method,
  1513. url: this.options.url,
  1514. data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
  1515. JSON.stringify(data) : data,
  1516. cache: this.options.cache,
  1517. contentType: this.options.contentType,
  1518. dataType: this.options.dataType,
  1519. success: function (res) {
  1520. res = calculateObjectValue(that.options, that.options.responseHandler, [res], res);
  1521. that.load(res);
  1522. that.trigger('load-success', res);
  1523. },
  1524. error: function (res) {
  1525. that.trigger('load-error', res.status, res);
  1526. },
  1527. complete: function () {
  1528. if (!silent) {
  1529. that.$tableLoading.hide();
  1530. }
  1531. }
  1532. });
  1533. if (this.options.ajax) {
  1534. calculateObjectValue(this, this.options.ajax, [request], null);
  1535. } else {
  1536. $.ajax(request);
  1537. }
  1538. };
  1539. BootstrapTable.prototype.initSearchText = function () {
  1540. if (this.options.search) {
  1541. if (this.options.searchText !== '') {
  1542. var $search = this.$toolbar.find('.search input');
  1543. $search.val(this.options.searchText);
  1544. this.onSearch({currentTarget: $search});
  1545. }
  1546. }
  1547. };
  1548. BootstrapTable.prototype.getCaret = function () {
  1549. var that = this;
  1550. $.each(this.$header.find('th'), function (i, th) {
  1551. $(th).find('.sortable').removeClass('desc asc').addClass($(th).data('field') === that.options.sortName ? that.options.sortOrder : 'both');
  1552. });
  1553. };
  1554. BootstrapTable.prototype.updateSelected = function () {
  1555. var checkAll = this.$selectItem.filter(':enabled').length &&
  1556. this.$selectItem.filter(':enabled').length ===
  1557. this.$selectItem.filter(':enabled').filter(':checked').length;
  1558. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll);
  1559. this.$selectItem.each(function () {
  1560. $(this).closest('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
  1561. });
  1562. };
  1563. BootstrapTable.prototype.updateRows = function () {
  1564. var that = this;
  1565. this.$selectItem.each(function () {
  1566. that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked');
  1567. });
  1568. };
  1569. BootstrapTable.prototype.resetRows = function () {
  1570. var that = this;
  1571. $.each(this.data, function (i, row) {
  1572. that.$selectAll.prop('checked', false);
  1573. that.$selectItem.prop('checked', false);
  1574. if (that.header.stateField) {
  1575. row[that.header.stateField] = false;
  1576. }
  1577. });
  1578. };
  1579. BootstrapTable.prototype.trigger = function (name) {
  1580. var args = Array.prototype.slice.call(arguments, 1);
  1581. name += '.bs.table';
  1582. this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
  1583. this.$el.trigger($.Event(name), args);
  1584. this.options.onAll(name, args);
  1585. this.$el.trigger($.Event('all.bs.table'), [name, args]);
  1586. };
  1587. BootstrapTable.prototype.resetHeader = function () {
  1588. // fix #61: the hidden table reset header bug.
  1589. // fix bug: get $el.css('width') error sometime (height = 500)
  1590. clearTimeout(this.timeoutId_);
  1591. this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0);
  1592. };
  1593. BootstrapTable.prototype.fitHeader = function () {
  1594. var that = this,
  1595. fixedBody,
  1596. scrollWidth,
  1597. focused,
  1598. focusedTemp;
  1599. if (that.$el.is(':hidden')) {
  1600. that.timeoutId_ = setTimeout($.proxy(that.fitHeader, that), 100);
  1601. return;
  1602. }
  1603. fixedBody = this.$tableBody.get(0);
  1604. scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
  1605. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
  1606. getScrollBarWidth() : 0;
  1607. this.$el.css('margin-top', -this.$header.outerHeight());
  1608. focused = $(':focus');
  1609. if (focused.length > 0) {
  1610. var $th = focused.parents('th');
  1611. if ($th.length > 0) {
  1612. var dataField = $th.attr('data-field');
  1613. if (dataField !== undefined) {
  1614. var $headerTh = this.$header.find("[data-field='" + dataField + "']");
  1615. if ($headerTh.length > 0) {
  1616. $headerTh.find(":input").addClass("focus-temp");
  1617. }
  1618. }
  1619. }
  1620. }
  1621. this.$header_ = this.$header.clone(true, true);
  1622. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
  1623. this.$tableHeader.css({
  1624. 'margin-right': scrollWidth
  1625. }).find('table').css('width', this.$el.outerWidth())
  1626. .html('').attr('class', this.$el.attr('class'))
  1627. .append(this.$header_);
  1628. focusedTemp = $('.focus-temp:visible:eq(0)');
  1629. if (focusedTemp.length > 0) {
  1630. focusedTemp.focus();
  1631. this.$header.find('.focus-temp').removeClass('focus-temp');
  1632. }
  1633. // fix bug: $.data() is not working as expected after $.append()
  1634. this.$header.find('th[data-field]').each(function (i) {
  1635. that.$header_.find(sprintf('th[data-field="%s"]', $(this).data('field'))).data($(this).data());
  1636. });
  1637. var visibleFields = this.getVisibleFields();
  1638. this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
  1639. var $this = $(this),
  1640. index = i;
  1641. if (that.options.detailView && !that.options.cardView) {
  1642. if (i === 0) {
  1643. that.$header_.find('th.detail').find('.fht-cell').width($this.innerWidth());
  1644. }
  1645. index = i - 1;
  1646. }
  1647. that.$header_.find(sprintf('th[data-field="%s"]', visibleFields[index]))
  1648. .find('.fht-cell').width($this.innerWidth());
  1649. });
  1650. // horizontal scroll event
  1651. // TODO: it's probably better improving the layout than binding to scroll event
  1652. this.$tableBody.off('scroll').on('scroll', function () {
  1653. that.$tableHeader.scrollLeft($(this).scrollLeft());
  1654. if (that.options.showFooter && !that.options.cardView) {
  1655. that.$tableFooter.scrollLeft($(this).scrollLeft());
  1656. }
  1657. });
  1658. that.trigger('post-header');
  1659. };
  1660. BootstrapTable.prototype.resetFooter = function () {
  1661. var that = this,
  1662. data = that.getData(),
  1663. html = [];
  1664. if (!this.options.showFooter || this.options.cardView) { //do nothing
  1665. return;
  1666. }
  1667. if (!this.options.cardView && this.options.detailView) {
  1668. html.push('<td><div class="th-inner">&nbsp;</div><div class="fht-cell"></div></td>');
  1669. }
  1670. $.each(this.columns, function (i, column) {
  1671. var falign = '', // footer align style
  1672. style = '',
  1673. class_ = sprintf(' class="%s"', column['class']);
  1674. if (!column.visible) {
  1675. return;
  1676. }
  1677. if (that.options.cardView && (!column.cardVisible)) {
  1678. return;
  1679. }
  1680. falign = sprintf('text-align: %s; ', column.falign ? column.falign : column.align);
  1681. style = sprintf('vertical-align: %s; ', column.valign);
  1682. html.push('<td', class_, sprintf(' style="%s"', falign + style), '>');
  1683. html.push('<div class="th-inner">');
  1684. html.push(calculateObjectValue(column, column.footerFormatter, [data], '&nbsp;') || '&nbsp;');
  1685. html.push('</div>');
  1686. html.push('<div class="fht-cell"></div>');
  1687. html.push('</div>');
  1688. html.push('</td>');
  1689. });
  1690. this.$tableFooter.find('tr').html(html.join(''));
  1691. clearTimeout(this.timeoutFooter_);
  1692. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this),
  1693. this.$el.is(':hidden') ? 100 : 0);
  1694. };
  1695. BootstrapTable.prototype.fitFooter = function () {
  1696. var that = this,
  1697. $footerTd,
  1698. elWidth,
  1699. scrollWidth;
  1700. clearTimeout(this.timeoutFooter_);
  1701. if (this.$el.is(':hidden')) {
  1702. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100);
  1703. return;
  1704. }
  1705. elWidth = this.$el.css('width');
  1706. scrollWidth = elWidth > this.$tableBody.width() ? getScrollBarWidth() : 0;
  1707. this.$tableFooter.css({
  1708. 'margin-right': scrollWidth
  1709. }).find('table').css('width', elWidth)
  1710. .attr('class', this.$el.attr('class'));
  1711. $footerTd = this.$tableFooter.find('td');
  1712. this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
  1713. var $this = $(this);
  1714. $footerTd.eq(i).find('.fht-cell').width($this.innerWidth());
  1715. });
  1716. };
  1717. BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
  1718. if (index === -1) {
  1719. return;
  1720. }
  1721. this.columns[index].visible = checked;
  1722. this.initHeader();
  1723. this.initSearch();
  1724. this.initPagination();
  1725. this.initBody();
  1726. if (this.options.showColumns) {
  1727. var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
  1728. if (needUpdate) {
  1729. $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
  1730. }
  1731. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  1732. $items.filter(':checked').prop('disabled', true);
  1733. }
  1734. }
  1735. };
  1736. BootstrapTable.prototype.toggleRow = function (index, uniqueId, visible) {
  1737. if (index === -1) {
  1738. return;
  1739. }
  1740. this.$body.find(typeof index !== 'undefined' ?
  1741. sprintf('tr[data-index="%s"]', index) :
  1742. sprintf('tr[data-uniqueid="%s"]', uniqueId))
  1743. [visible ? 'show' : 'hide']();
  1744. };
  1745. BootstrapTable.prototype.getVisibleFields = function () {
  1746. var that = this,
  1747. visibleFields = [];
  1748. $.each(this.header.fields, function (j, field) {
  1749. var column = that.columns[getFieldIndex(that.columns, field)];
  1750. if (!column.visible) {
  1751. return;
  1752. }
  1753. visibleFields.push(field);
  1754. });
  1755. return visibleFields;
  1756. };
  1757. // PUBLIC FUNCTION DEFINITION
  1758. // =======================
  1759. BootstrapTable.prototype.resetView = function (params) {
  1760. var padding = 0;
  1761. if (params && params.height) {
  1762. this.options.height = params.height;
  1763. }
  1764. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  1765. this.$selectItem.length === this.$selectItem.filter(':checked').length);
  1766. if (this.options.height) {
  1767. var toolbarHeight = getRealHeight(this.$toolbar),
  1768. paginationHeight = getRealHeight(this.$pagination),
  1769. height = this.options.height - toolbarHeight - paginationHeight;
  1770. this.$tableContainer.css('height', height + 'px');
  1771. }
  1772. if (this.options.cardView) {
  1773. // remove the element css
  1774. this.$el.css('margin-top', '0');
  1775. this.$tableContainer.css('padding-bottom', '0');
  1776. return;
  1777. }
  1778. if (this.options.showHeader && this.options.height) {
  1779. this.$tableHeader.show();
  1780. this.resetHeader();
  1781. padding += this.$header.outerHeight();
  1782. } else {
  1783. this.$tableHeader.hide();
  1784. this.trigger('post-header');
  1785. }
  1786. if (this.options.showFooter) {
  1787. this.resetFooter();
  1788. if (this.options.height) {
  1789. padding += this.$tableFooter.outerHeight() + 1;
  1790. }
  1791. }
  1792. // Assign the correct sortable arrow
  1793. this.getCaret();
  1794. this.$tableContainer.css('padding-bottom', padding + 'px');
  1795. this.trigger('reset-view');
  1796. };
  1797. BootstrapTable.prototype.getData = function (useCurrentPage) {
  1798. return (this.searchText || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) ?
  1799. (useCurrentPage ? this.data.slice(this.pageFrom - 1, this.pageTo) : this.data) :
  1800. (useCurrentPage ? this.options.data.slice(this.pageFrom - 1, this.pageTo) : this.options.data);
  1801. };
  1802. BootstrapTable.prototype.load = function (data) {
  1803. var fixedScroll = false;
  1804. // #431: support pagination
  1805. if (this.options.sidePagination === 'server') {
  1806. this.options.totalRows = data.total;
  1807. fixedScroll = data.fixedScroll;
  1808. data = data[this.options.dataField];
  1809. } else if (!$.isArray(data)) { // support fixedScroll
  1810. fixedScroll = data.fixedScroll;
  1811. data = data.data;
  1812. }
  1813. this.initData(data);
  1814. this.initSearch();
  1815. this.initPagination();
  1816. this.initBody(fixedScroll);
  1817. };
  1818. BootstrapTable.prototype.append = function (data) {
  1819. this.initData(data, 'append');
  1820. this.initSearch();
  1821. this.initPagination();
  1822. this.initBody(true);
  1823. };
  1824. BootstrapTable.prototype.prepend = function (data) {
  1825. this.initData(data, 'prepend');
  1826. this.initSearch();
  1827. this.initPagination();
  1828. this.initBody(true);
  1829. };
  1830. BootstrapTable.prototype.remove = function (params) {
  1831. var len = this.options.data.length,
  1832. i, row;
  1833. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  1834. return;
  1835. }
  1836. for (i = len - 1; i >= 0; i--) {
  1837. row = this.options.data[i];
  1838. if (!row.hasOwnProperty(params.field)) {
  1839. continue;
  1840. }
  1841. if ($.inArray(row[params.field], params.values) !== -1) {
  1842. this.options.data.splice(i, 1);
  1843. }
  1844. }
  1845. if (len === this.options.data.length) {
  1846. return;
  1847. }
  1848. this.initSearch();
  1849. this.initPagination();
  1850. this.initBody(true);
  1851. };
  1852. BootstrapTable.prototype.removeAll = function () {
  1853. if (this.options.data.length > 0) {
  1854. this.options.data.splice(0, this.options.data.length);
  1855. this.initSearch();
  1856. this.initPagination();
  1857. this.initBody(true);
  1858. }
  1859. };
  1860. BootstrapTable.prototype.getRowByUniqueId = function (id) {
  1861. var uniqueId = this.options.uniqueId,
  1862. len = this.options.data.length,
  1863. dataRow = null,
  1864. i, row, rowUniqueId;
  1865. for (i = len - 1; i >= 0; i--) {
  1866. row = this.options.data[i];
  1867. if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
  1868. rowUniqueId = row[uniqueId];
  1869. } else if(row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
  1870. rowUniqueId = row._data[uniqueId];
  1871. } else {
  1872. continue;
  1873. }
  1874. if (typeof rowUniqueId === 'string') {
  1875. id = id.toString();
  1876. } else if (typeof rowUniqueId === 'number') {
  1877. if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
  1878. id = parseInt(id);
  1879. } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
  1880. id = parseFloat(id);
  1881. }
  1882. }
  1883. if (rowUniqueId === id) {
  1884. dataRow = row;
  1885. break;
  1886. }
  1887. }
  1888. return dataRow;
  1889. };
  1890. BootstrapTable.prototype.removeByUniqueId = function (id) {
  1891. var len = this.options.data.length,
  1892. row = this.getRowByUniqueId(id);
  1893. if (row) {
  1894. this.options.data.splice(this.options.data.indexOf(row), 1);
  1895. }
  1896. if (len === this.options.data.length) {
  1897. return;
  1898. }
  1899. this.initSearch();
  1900. this.initPagination();
  1901. this.initBody(true);
  1902. };
  1903. BootstrapTable.prototype.updateByUniqueId = function (params) {
  1904. var rowId;
  1905. if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
  1906. return;
  1907. }
  1908. rowId = $.inArray(this.getRowByUniqueId(params.id), this.options.data);
  1909. if (rowId === -1) {
  1910. return;
  1911. }
  1912. $.extend(this.data[rowId], params.row);
  1913. this.initSort();
  1914. this.initBody(true);
  1915. };
  1916. BootstrapTable.prototype.insertRow = function (params) {
  1917. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1918. return;
  1919. }
  1920. this.data.splice(params.index, 0, params.row);
  1921. this.initSearch();
  1922. this.initPagination();
  1923. this.initSort();
  1924. this.initBody(true);
  1925. };
  1926. BootstrapTable.prototype.updateRow = function (params) {
  1927. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1928. return;
  1929. }
  1930. $.extend(this.data[params.index], params.row);
  1931. this.initSort();
  1932. this.initBody(true);
  1933. };
  1934. BootstrapTable.prototype.showRow = function (params) {
  1935. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('uniqueId')) {
  1936. return;
  1937. }
  1938. this.toggleRow(params.index, params.uniqueId, true);
  1939. };
  1940. BootstrapTable.prototype.hideRow = function (params) {
  1941. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('uniqueId')) {
  1942. return;
  1943. }
  1944. this.toggleRow(params.index, params.uniqueId, false);
  1945. };
  1946. BootstrapTable.prototype.getRowsHidden = function (show) {
  1947. var rows = $(this.$body[0]).children().filter(':hidden'),
  1948. i = 0;
  1949. if (show) {
  1950. for (; i < rows.length; i++) {
  1951. $(rows[i]).show();
  1952. }
  1953. }
  1954. return rows;
  1955. };
  1956. BootstrapTable.prototype.mergeCells = function (options) {
  1957. var row = options.index,
  1958. col = $.inArray(options.field, this.getVisibleFields()),
  1959. rowspan = options.rowspan || 1,
  1960. colspan = options.colspan || 1,
  1961. i, j,
  1962. $tr = this.$body.find('>tr'),
  1963. $td;
  1964. if (this.options.detailView && !this.options.cardView) {
  1965. col += 1;
  1966. }
  1967. $td = $tr.eq(row).find('>td').eq(col);
  1968. if (row < 0 || col < 0 || row >= this.data.length) {
  1969. return;
  1970. }
  1971. for (i = row; i < row + rowspan; i++) {
  1972. for (j = col; j < col + colspan; j++) {
  1973. $tr.eq(i).find('>td').eq(j).hide();
  1974. }
  1975. }
  1976. $td.attr('rowspan', rowspan).attr('colspan', colspan).show();
  1977. };
  1978. BootstrapTable.prototype.updateCell = function (params) {
  1979. if (!params.hasOwnProperty('index') ||
  1980. !params.hasOwnProperty('field') ||
  1981. !params.hasOwnProperty('value')) {
  1982. return;
  1983. }
  1984. this.data[params.index][params.field] = params.value;
  1985. this.initSort();
  1986. this.initBody(true);
  1987. };
  1988. BootstrapTable.prototype.getOptions = function () {
  1989. return this.options;
  1990. };
  1991. BootstrapTable.prototype.getSelections = function () {
  1992. var that = this;
  1993. return $.grep(this.data, function (row) {
  1994. return row[that.header.stateField];
  1995. });
  1996. };
  1997. BootstrapTable.prototype.getAllSelections = function () {
  1998. var that = this;
  1999. return $.grep(this.options.data, function (row) {
  2000. return row[that.header.stateField];
  2001. });
  2002. };
  2003. BootstrapTable.prototype.checkAll = function () {
  2004. this.checkAll_(true);
  2005. };
  2006. BootstrapTable.prototype.uncheckAll = function () {
  2007. this.checkAll_(false);
  2008. };
  2009. BootstrapTable.prototype.checkAll_ = function (checked) {
  2010. var rows;
  2011. if (!checked) {
  2012. rows = this.getSelections();
  2013. }
  2014. this.$selectAll.add(this.$selectAll_).prop('checked', checked);
  2015. this.$selectItem.filter(':enabled').prop('checked', checked);
  2016. this.updateRows();
  2017. if (checked) {
  2018. rows = this.getSelections();
  2019. }
  2020. this.trigger(checked ? 'check-all' : 'uncheck-all', rows);
  2021. };
  2022. BootstrapTable.prototype.check = function (index) {
  2023. this.check_(true, index);
  2024. };
  2025. BootstrapTable.prototype.uncheck = function (index) {
  2026. this.check_(false, index);
  2027. };
  2028. BootstrapTable.prototype.check_ = function (checked, index) {
  2029. var $el = this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  2030. this.data[index][this.header.stateField] = checked;
  2031. this.updateSelected();
  2032. this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el);
  2033. };
  2034. BootstrapTable.prototype.checkBy = function (obj) {
  2035. this.checkBy_(true, obj);
  2036. };
  2037. BootstrapTable.prototype.uncheckBy = function (obj) {
  2038. this.checkBy_(false, obj);
  2039. };
  2040. BootstrapTable.prototype.checkBy_ = function (checked, obj) {
  2041. if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
  2042. return;
  2043. }
  2044. var that = this,
  2045. rows = [];
  2046. $.each(this.options.data, function (index, row) {
  2047. if (!row.hasOwnProperty(obj.field)) {
  2048. return false;
  2049. }
  2050. if ($.inArray(row[obj.field], obj.values) !== -1) {
  2051. var $el = that.$selectItem.filter(':enabled')
  2052. .filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  2053. row[that.header.stateField] = checked;
  2054. rows.push(row);
  2055. that.trigger(checked ? 'check' : 'uncheck', row, $el);
  2056. }
  2057. });
  2058. this.updateSelected();
  2059. this.trigger(checked ? 'check-some' : 'uncheck-some', rows);
  2060. };
  2061. BootstrapTable.prototype.destroy = function () {
  2062. this.$el.insertBefore(this.$container);
  2063. $(this.options.toolbar).insertBefore(this.$el);
  2064. this.$container.next().remove();
  2065. this.$container.remove();
  2066. this.$el.html(this.$el_.html())
  2067. .css('margin-top', '0')
  2068. .attr('class', this.$el_.attr('class') || ''); // reset the class
  2069. };
  2070. BootstrapTable.prototype.showLoading = function () {
  2071. this.$tableLoading.show();
  2072. };
  2073. BootstrapTable.prototype.hideLoading = function () {
  2074. this.$tableLoading.hide();
  2075. };
  2076. BootstrapTable.prototype.togglePagination = function () {
  2077. this.options.pagination = !this.options.pagination;
  2078. var button = this.$toolbar.find('button[name="paginationSwitch"] i');
  2079. if (this.options.pagination) {
  2080. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown);
  2081. } else {
  2082. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp);
  2083. }
  2084. this.updatePagination();
  2085. };
  2086. BootstrapTable.prototype.refresh = function (params) {
  2087. if (params && params.url) {
  2088. this.options.url = params.url;
  2089. this.options.pageNumber = 1;
  2090. }
  2091. this.initServer(params && params.silent, params && params.query);
  2092. };
  2093. BootstrapTable.prototype.resetWidth = function () {
  2094. if (this.options.showHeader && this.options.height) {
  2095. this.fitHeader();
  2096. }
  2097. if (this.options.showFooter) {
  2098. this.fitFooter();
  2099. }
  2100. };
  2101. BootstrapTable.prototype.showColumn = function (field) {
  2102. this.toggleColumn(getFieldIndex(this.columns, field), true, true);
  2103. };
  2104. BootstrapTable.prototype.hideColumn = function (field) {
  2105. this.toggleColumn(getFieldIndex(this.columns, field), false, true);
  2106. };
  2107. BootstrapTable.prototype.getHiddenColumns = function () {
  2108. return $.grep(this.columns, function (column) {
  2109. return !column.visible;
  2110. });
  2111. };
  2112. BootstrapTable.prototype.filterBy = function (columns) {
  2113. this.filterColumns = $.isEmptyObject(columns) ? {} : columns;
  2114. this.options.pageNumber = 1;
  2115. this.initSearch();
  2116. this.updatePagination();
  2117. };
  2118. BootstrapTable.prototype.scrollTo = function (value) {
  2119. if (typeof value === 'string') {
  2120. value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0;
  2121. }
  2122. if (typeof value === 'number') {
  2123. this.$tableBody.scrollTop(value);
  2124. }
  2125. if (typeof value === 'undefined') {
  2126. return this.$tableBody.scrollTop();
  2127. }
  2128. };
  2129. BootstrapTable.prototype.getScrollPosition = function () {
  2130. return this.scrollTo();
  2131. };
  2132. BootstrapTable.prototype.selectPage = function (page) {
  2133. if (page > 0 && page <= this.options.totalPages) {
  2134. this.options.pageNumber = page;
  2135. this.updatePagination();
  2136. }
  2137. };
  2138. BootstrapTable.prototype.prevPage = function () {
  2139. if (this.options.pageNumber > 1) {
  2140. this.options.pageNumber--;
  2141. this.updatePagination();
  2142. }
  2143. };
  2144. BootstrapTable.prototype.nextPage = function () {
  2145. if (this.options.pageNumber < this.options.totalPages) {
  2146. this.options.pageNumber++;
  2147. this.updatePagination();
  2148. }
  2149. };
  2150. BootstrapTable.prototype.toggleView = function () {
  2151. this.options.cardView = !this.options.cardView;
  2152. this.initHeader();
  2153. // Fixed remove toolbar when click cardView button.
  2154. //that.initToolbar();
  2155. this.initBody();
  2156. this.trigger('toggle', this.options.cardView);
  2157. };
  2158. BootstrapTable.prototype.refreshOptions = function (options) {
  2159. //If the objects are equivalent then avoid the call of destroy / init methods
  2160. if (compareObjects(this.options, options, false)) {
  2161. return;
  2162. }
  2163. this.options = $.extend(this.options, options);
  2164. this.trigger('refresh-options', this.options);
  2165. this.destroy();
  2166. this.init();
  2167. };
  2168. BootstrapTable.prototype.resetSearch = function (text) {
  2169. var $search = this.$toolbar.find('.search input');
  2170. $search.val(text || '');
  2171. this.onSearch({currentTarget: $search});
  2172. };
  2173. BootstrapTable.prototype.expandRow_ = function (expand, index) {
  2174. var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', index));
  2175. if ($tr.next().is('tr.detail-view') === (expand ? false : true)) {
  2176. $tr.find('> td > .detail-icon').click();
  2177. }
  2178. };
  2179. BootstrapTable.prototype.expandRow = function (index) {
  2180. this.expandRow_(true, index);
  2181. };
  2182. BootstrapTable.prototype.collapseRow = function (index) {
  2183. this.expandRow_(false, index);
  2184. };
  2185. BootstrapTable.prototype.expandAllRows = function (isSubTable) {
  2186. if (isSubTable) {
  2187. var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', 0)),
  2188. that = this,
  2189. detailIcon = null,
  2190. executeInterval = false,
  2191. idInterval = -1;
  2192. if (!$tr.next().is('tr.detail-view')) {
  2193. $tr.find('> td > .detail-icon').click();
  2194. executeInterval = true;
  2195. } else if (!$tr.next().next().is('tr.detail-view')) {
  2196. $tr.next().find(".detail-icon").click();
  2197. executeInterval = true;
  2198. }
  2199. if (executeInterval) {
  2200. try {
  2201. idInterval = setInterval(function () {
  2202. detailIcon = that.$body.find("tr.detail-view").last().find(".detail-icon");
  2203. if (detailIcon.length > 0) {
  2204. detailIcon.click();
  2205. } else {
  2206. clearInterval(idInterval);
  2207. }
  2208. }, 1);
  2209. } catch (ex) {
  2210. clearInterval(idInterval);
  2211. }
  2212. }
  2213. } else {
  2214. var trs = this.$body.children();
  2215. for (var i = 0; i < trs.length; i++) {
  2216. this.expandRow_(true, $(trs[i]).data("index"));
  2217. }
  2218. }
  2219. };
  2220. BootstrapTable.prototype.collapseAllRows = function (isSubTable) {
  2221. if (isSubTable) {
  2222. this.expandRow_(false, 0);
  2223. } else {
  2224. var trs = this.$body.children();
  2225. for (var i = 0; i < trs.length; i++) {
  2226. this.expandRow_(false, $(trs[i]).data("index"));
  2227. }
  2228. }
  2229. };
  2230. // BOOTSTRAP TABLE PLUGIN DEFINITION
  2231. // =======================
  2232. var allowedMethods = [
  2233. 'getOptions',
  2234. 'getSelections', 'getAllSelections', 'getData',
  2235. 'load', 'append', 'prepend', 'remove', 'removeAll',
  2236. 'insertRow', 'updateRow', 'updateCell', 'updateByUniqueId', 'removeByUniqueId',
  2237. 'getRowByUniqueId', 'showRow', 'hideRow', 'getRowsHidden',
  2238. 'mergeCells',
  2239. 'checkAll', 'uncheckAll',
  2240. 'check', 'uncheck',
  2241. 'checkBy', 'uncheckBy',
  2242. 'refresh',
  2243. 'resetView',
  2244. 'resetWidth',
  2245. 'destroy',
  2246. 'showLoading', 'hideLoading',
  2247. 'showColumn', 'hideColumn', 'getHiddenColumns',
  2248. 'filterBy',
  2249. 'scrollTo',
  2250. 'getScrollPosition',
  2251. 'selectPage', 'prevPage', 'nextPage',
  2252. 'togglePagination',
  2253. 'toggleView',
  2254. 'refreshOptions',
  2255. 'resetSearch',
  2256. 'expandRow', 'collapseRow', 'expandAllRows', 'collapseAllRows'
  2257. ];
  2258. $.fn.bootstrapTable = function (option) {
  2259. var value,
  2260. args = Array.prototype.slice.call(arguments, 1);
  2261. this.each(function () {
  2262. var $this = $(this),
  2263. data = $this.data('bootstrap.table'),
  2264. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
  2265. typeof option === 'object' && option);
  2266. if (typeof option === 'string') {
  2267. if ($.inArray(option, allowedMethods) < 0) {
  2268. throw new Error("Unknown method: " + option);
  2269. }
  2270. if (!data) {
  2271. return;
  2272. }
  2273. value = data[option].apply(data, args);
  2274. if (option === 'destroy') {
  2275. $this.removeData('bootstrap.table');
  2276. }
  2277. }
  2278. if (!data) {
  2279. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  2280. }
  2281. });
  2282. return typeof value === 'undefined' ? this : value;
  2283. };
  2284. $.fn.bootstrapTable.Constructor = BootstrapTable;
  2285. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
  2286. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
  2287. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES;
  2288. $.fn.bootstrapTable.methods = allowedMethods;
  2289. $.fn.bootstrapTable.utils = {
  2290. sprintf: sprintf,
  2291. getFieldIndex: getFieldIndex,
  2292. compareObjects: compareObjects,
  2293. calculateObjectValue: calculateObjectValue
  2294. };
  2295. // BOOTSTRAP TABLE INIT
  2296. // =======================
  2297. $(function () {
  2298. $('[data-toggle="table"]').bootstrapTable();
  2299. });
  2300. }(jQuery);