bootstrap-table.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.1.3
  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. if (flag) {
  24. return str;
  25. }
  26. return '';
  27. };
  28. var getPropertyFromOther = function (list, from, to, value) {
  29. var result = '';
  30. $.each(list, function (i, item) {
  31. if (item[from] === value) {
  32. result = item[to];
  33. return false;
  34. }
  35. return true;
  36. });
  37. return result;
  38. };
  39. // BOOTSTRAP TABLE CLASS DEFINITION
  40. // ======================
  41. var BootstrapTable = function (el, options) {
  42. this.options = options;
  43. this.$el = $(el);
  44. this.$el_ = this.$el.clone();
  45. this.init();
  46. };
  47. BootstrapTable.DEFAULTS = {
  48. classes: 'table table-hover',
  49. height: undefined,
  50. undefinedText: '-',
  51. sortName: undefined,
  52. sortOrder: 'asc',
  53. striped: false,
  54. columns: [],
  55. data: [],
  56. method: 'get',
  57. url: undefined,
  58. contentType: 'application/json',
  59. queryParams: function (params) {return {};},
  60. queryParamsType: undefined,
  61. responseHandler: function (res) {return res;},
  62. pagination: false,
  63. sidePagination: 'client', // client or server
  64. totalRows: 0, // server side need to set
  65. pageNumber: 1,
  66. pageSize: 10,
  67. pageList: [10, 25, 50, 100],
  68. search: false,
  69. selectItemName: 'btSelectItem',
  70. showHeader: true,
  71. showColumns: false,
  72. minimunCountColumns: 1,
  73. idField: undefined,
  74. cardView: false,
  75. clickToSelect: false,
  76. singleSelect: false,
  77. toolbar: undefined,
  78. checkboxHeader: true,
  79. rowStyle: function (row, index) {return {};},
  80. formatLoadingMessage: function () {
  81. return 'Loading, please wait…';
  82. },
  83. formatRecordsPerPage: function (pageNumber) {
  84. return sprintf('%s records per page', pageNumber);
  85. },
  86. formatShowingRows: function (pageFrom, pageTo, totalRows) {
  87. return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows);
  88. },
  89. formatSearch: function () {
  90. return 'Search';
  91. },
  92. formatNoMatches: function () {
  93. return 'No matching records found';
  94. },
  95. onAll: function (name, args) {return false;},
  96. onClickRow: function (item, $element) {return false;},
  97. onDblClickRow: function (item, $element) {return false;},
  98. onSort: function (name, order) {return false;},
  99. onCheck: function (row) {return false;},
  100. onUncheck: function (row) {return false;},
  101. onCheckAll: function () {return false;},
  102. onUncheckAll: function () {return false;},
  103. onLoadSuccess: function (data) {return false;},
  104. onLoadError: function (status) {return false;}
  105. };
  106. BootstrapTable.COLUMN_DEFAULTS = {
  107. radio: false,
  108. checkbox: false,
  109. field: undefined,
  110. title: undefined,
  111. 'class': undefined,
  112. align: undefined, // left, right, center
  113. valign: undefined, // top, middle, bottom
  114. width: undefined,
  115. sortable: false,
  116. order: 'asc', // asc, desc
  117. visible: true,
  118. switchable: true,
  119. formatter: undefined,
  120. events: undefined,
  121. sorter: undefined
  122. };
  123. BootstrapTable.EVENTS = {
  124. 'all.bs.table': 'onAll',
  125. 'click-row.bs.table': 'onClickRow',
  126. 'dbl-click-row.bs.table': 'onDblClickRow',
  127. 'sort.bs.table': 'onSort',
  128. 'check.bs.table': 'onCheck',
  129. 'uncheck.bs.table': 'onUncheck',
  130. 'check-all.bs.table': 'onCheckAll',
  131. 'uncheck-all.bs.table': 'onUncheckAll',
  132. 'load-success.bs.table': 'onLoadSuccess',
  133. 'load-error.bs.table': 'onLoadError'
  134. };
  135. BootstrapTable.prototype.init = function () {
  136. this.initContainer();
  137. this.initTable();
  138. this.initHeader();
  139. this.initData();
  140. this.initToolbar();
  141. this.initPagination();
  142. this.initBody();
  143. this.initServer();
  144. };
  145. BootstrapTable.prototype.initContainer = function () {
  146. this.$container = $([
  147. '<div class="bootstrap-table">',
  148. '<div class="fixed-table-toolbar"></div>',
  149. '<div class="fixed-table-container">',
  150. '<div class="fixed-table-header"><table></table></div>',
  151. '<div class="fixed-table-body">',
  152. '<div class="fixed-table-loading">',
  153. this.options.formatLoadingMessage(),
  154. '</div>',
  155. '</div>',
  156. '<div class="fixed-table-pagination"></div>',
  157. '</div>',
  158. '</div>'].join(''));
  159. this.$container.insertAfter(this.$el);
  160. this.$container.find('.fixed-table-body').append(this.$el);
  161. this.$container.after('<div class="clearfix"></div>');
  162. this.$loading = this.$container.find('.fixed-table-loading');
  163. this.$el.addClass(this.options.classes);
  164. if (this.options.striped) {
  165. this.$el.addClass('table-striped');
  166. }
  167. };
  168. BootstrapTable.prototype.initTable = function () {
  169. var that = this,
  170. columns = [],
  171. data = [];
  172. this.$header = this.$el.find('thead');
  173. if (!this.$header.length) {
  174. this.$header = $('<thead></thead>').appendTo(this.$el);
  175. }
  176. if (!this.$header.find('tr').length) {
  177. this.$header.append('<tr></tr>');
  178. }
  179. this.$header.find('th').each(function () {
  180. var column = $.extend({}, {
  181. title: $(this).html(),
  182. 'class': $(this).attr('class')
  183. }, $(this).data());
  184. columns.push(column);
  185. });
  186. this.options.columns = $.extend({}, columns, this.options.columns);
  187. $.each(this.options.columns, function (i, column) {
  188. that.options.columns[i] = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column);
  189. });
  190. this.$el.find('tbody tr').each(function () {
  191. var row = {};
  192. $(this).find('td').each(function (i) {
  193. row[that.options.columns[i].field] = $(this).html();
  194. });
  195. data.push(row);
  196. });
  197. this.options.data = data;
  198. };
  199. BootstrapTable.prototype.initHeader = function () {
  200. var that = this,
  201. visibleColumns = [],
  202. html = [];
  203. this.header = {
  204. fields: [],
  205. styles: [],
  206. formatters: [],
  207. events: [],
  208. sorters: []
  209. };
  210. $.each(this.options.columns, function (i, column) {
  211. var text = '',
  212. style = sprintf('text-align: %s; ', column.align) +
  213. sprintf('vertical-align: %s; ', column.valign),
  214. order = that.options.sortOrder || column.order;
  215. if (!column.visible) {
  216. return;
  217. }
  218. visibleColumns.push(column);
  219. that.header.fields.push(column.field);
  220. that.header.styles.push(style);
  221. that.header.formatters.push(column.formatter);
  222. that.header.events.push(column.events);
  223. that.header.sorters.push(column.sorter);
  224. style += sprintf('width: %spx; ', column.checkbox || column.radio ? 36 : column.width);
  225. style += column.sortable ? 'cursor: pointer; ' : '';
  226. html.push('<th',
  227. column.checkbox || column.radio ? ' class="bs-checkbox"' :
  228. sprintf(' class="%s"', column['class']),
  229. sprintf(' style="%s"', style),
  230. '>');
  231. html.push('<div class="th-inner">');
  232. text = column.title;
  233. if (that.options.sortName === column.field && column.sortable) {
  234. text += that.getCaretHtml();
  235. }
  236. if (column.checkbox) {
  237. if (!that.options.singleSelect && that.options.checkboxHeader) {
  238. text = '<input name="btSelectAll" type="checkbox" />';
  239. }
  240. that.header.stateField = column.field;
  241. }
  242. if (column.radio) {
  243. text = '';
  244. that.header.stateField = column.field;
  245. that.options.singleSelect = true;
  246. }
  247. html.push(text);
  248. html.push('</div>');
  249. html.push('<div class="fht-cell"></div>');
  250. html.push('</th>');
  251. });
  252. this.$header.find('tr').html(html.join(''));
  253. this.$header.find('th').each(function (i) {
  254. $(this).data(visibleColumns[i]);
  255. if (visibleColumns[i].sortable) {
  256. $(this).off('click').on('click', $.proxy(that.onSort, that));
  257. }
  258. });
  259. if (!this.options.showHeader || this.options.cardView) {
  260. this.$header.hide();
  261. this.$container.find('.fixed-table-header').hide();
  262. this.$loading.css('top', 0);
  263. }
  264. this.$selectAll = this.$header.find('[name="btSelectAll"]');
  265. this.$selectAll.off('click').on('click', function () {
  266. var checked = $(this).prop('checked');
  267. that[checked ? 'checkAll' : 'uncheckAll']();
  268. });
  269. };
  270. BootstrapTable.prototype.initData = function (data, append) {
  271. if (append) {
  272. this.data = this.data.concat(data);
  273. } else {
  274. this.data = data || this.options.data;
  275. }
  276. this.options.data = this.data;
  277. this.initSort();
  278. };
  279. BootstrapTable.prototype.initSort = function () {
  280. var name = this.options.sortName,
  281. order = this.options.sortOrder === 'desc' ? -1 : 1,
  282. index = $.inArray(this.options.sortName, this.header.fields);
  283. if (index !== -1) {
  284. var sorter = this.header.sorters[index];
  285. this.data.sort(function (a, b) {
  286. if (typeof sorter === 'function') {
  287. return order * sorter(a[name], b[name]);
  288. }
  289. if (typeof sorter === 'string') {
  290. return order * eval(sorter + '(a[name], b[name])'); // eval ?
  291. }
  292. if (a[name] === b[name]) {
  293. return 0;
  294. }
  295. if (a[name] < b[name]) {
  296. return order * -1;
  297. }
  298. return order;
  299. });
  300. }
  301. };
  302. BootstrapTable.prototype.onSort = function (event) {
  303. var $this = $(event.currentTarget),
  304. $this_ = this.$header.find('th').eq($this.index());
  305. this.$header.add(this.$header_).find('span.order').remove();
  306. this.options.sortName = $this.data('field');
  307. this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
  308. this.trigger('sort', this.options.sortName, this.options.sortOrder);
  309. $this.add($this_).data('order', this.options.sortOrder)
  310. .find('.th-inner').append(this.getCaretHtml());
  311. if (this.options.sidePagination === 'server') {
  312. this.initServer();
  313. return;
  314. }
  315. this.initSort();
  316. this.initBody();
  317. };
  318. BootstrapTable.prototype.initToolbar = function () {
  319. var that = this,
  320. html = [],
  321. timeoutId = 0,
  322. $keepOpen,
  323. $search;
  324. this.$toolbar = this.$container.find('.fixed-table-toolbar').html('');
  325. if (typeof this.options.toolbar === 'string') {
  326. $('<div class="bars pull-left"></div>')
  327. .appendTo(this.$toolbar)
  328. .append($(this.options.toolbar));
  329. }
  330. if (this.options.showColumns) {
  331. html = [];
  332. html.push('<div class="columns pull-right keep-open">',
  333. '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">',
  334. '<i class="glyphicon glyphicon-th icon-th"></i>',
  335. ' <span class="caret"></span>',
  336. '</button>',
  337. '<ul class="dropdown-menu" role="menu">');
  338. $.each(this.options.columns, function (i, column) {
  339. if (column.radio || column.checkbox) {
  340. return;
  341. }
  342. var checked = column.visible ? ' checked="checked"' : '';
  343. if (column.switchable) {
  344. html.push(sprintf('<li>' +
  345. '<label><input type="checkbox" value="%s"%s> %s</label>' +
  346. '</li>', i, checked, column.title));
  347. }
  348. });
  349. html.push('</ul>',
  350. '</div>');
  351. this.$toolbar.append(html.join(''));
  352. $keepOpen = this.$toolbar.find('.keep-open');
  353. $keepOpen.find('li').off('click').on('click', function (event) {
  354. event.stopImmediatePropagation();
  355. });
  356. $keepOpen.find('input').off('click').on('click', function () {
  357. var $this = $(this),
  358. $items = $keepOpen.find('input').prop('disabled', false);
  359. that.options.columns[$this.val()].visible = $this.prop('checked');
  360. that.initHeader();
  361. that.initBody();
  362. if ($items.filter(':checked').length <= that.options.minimunCountColumns) {
  363. $items.filter(':checked').prop('disabled', true);
  364. }
  365. });
  366. }
  367. if (this.options.search) {
  368. html = [];
  369. html.push(
  370. '<div class="pull-right search">',
  371. sprintf('<input class="form-control" type="text" placeholder="%s">',
  372. this.options.formatSearch()),
  373. '</div>');
  374. this.$toolbar.append(html.join(''));
  375. $search = this.$toolbar.find('.search input');
  376. $search.off('keyup').on('keyup', function (event) {
  377. clearTimeout(timeoutId); // doesn't matter if it's 0
  378. timeoutId = setTimeout($.proxy(that.onSearch, that), 500, event); // 500ms
  379. });
  380. }
  381. };
  382. BootstrapTable.prototype.onSearch = function (event) {
  383. var that = this,
  384. text = $.trim($(event.currentTarget).val());
  385. if (text === this.searchText) {
  386. return;
  387. }
  388. this.searchText = text;
  389. if (this.options.sidePagination !== 'server') {
  390. var s = that.searchText.toLowerCase();
  391. this.data = $.grep(this.options.data, function (item) {
  392. for (var key in item) {
  393. if ((typeof item[key] === 'string' ||
  394. typeof item[key] === 'number') &&
  395. (item[key] + '').toLowerCase().indexOf(s) !== -1) {
  396. return true;
  397. }
  398. }
  399. return false;
  400. });
  401. }
  402. this.options.pageNumber = 1;
  403. this.updatePagination();
  404. };
  405. BootstrapTable.prototype.initPagination = function () {
  406. this.$pagination = this.$container.find('.fixed-table-pagination');
  407. if (!this.options.pagination) {
  408. return;
  409. }
  410. var that = this,
  411. html = [],
  412. i, from, to,
  413. $pageList,
  414. $first, $pre,
  415. $next, $last,
  416. $number,
  417. data = this.searchText ? this.data : this.options.data;
  418. if (this.options.sidePagination !== 'server') {
  419. this.options.totalRows = data.length;
  420. }
  421. this.totalPages = 0;
  422. if (this.options.totalRows) {
  423. this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
  424. }
  425. if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
  426. this.options.pageNumber = this.totalPages;
  427. }
  428. this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
  429. this.pageTo = this.options.pageNumber * this.options.pageSize;
  430. if (this.pageTo > this.options.totalRows) {
  431. this.pageTo = this.options.totalRows;
  432. }
  433. html.push(
  434. '<div class="pull-left pagination-detail">',
  435. '<span class="pagination-info">',
  436. this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
  437. '</span>');
  438. html.push('<span class="page-list">');
  439. var pageNumber = [
  440. '<span class="btn-group dropup">',
  441. '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">',
  442. '<span class="page-size">',
  443. this.options.pageSize,
  444. '</span>',
  445. ' <span class="caret"></span>',
  446. '</button>',
  447. '<ul class="dropdown-menu" role="menu">'],
  448. pageList = this.options.pageList;
  449. if (typeof this.options.pageList === 'string') {
  450. pageList = eval(this.options.pageList);
  451. }
  452. $.each(pageList, function (i, page) {
  453. var active = page === that.options.pageSize ? ' class="active"' : '';
  454. pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page));
  455. });
  456. pageNumber.push('</ul></span>');
  457. html.push(this.options.formatRecordsPerPage(pageNumber.join('')));
  458. html.push('</span>');
  459. html.push('</div>',
  460. '<div class="pull-right">',
  461. '<ul class="pagination">',
  462. '<li class="page-first"><a href="javascript:void(0)">&lt;&lt;</a></li>',
  463. '<li class="page-pre"><a href="javascript:void(0)">&lt;</a></li>');
  464. if (this.totalPages < 5) {
  465. from = 1;
  466. to = this.totalPages;
  467. } else {
  468. from = this.options.pageNumber - 2;
  469. to = from + 4;
  470. if (from < 1) {
  471. from = 1;
  472. to = 5;
  473. }
  474. if (to > this.totalPages) {
  475. to = this.totalPages;
  476. from = to - 4;
  477. }
  478. }
  479. for (i = from; i <= to; i++) {
  480. html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
  481. '<a href="javascript:void(0)">', i ,'</a>',
  482. '</li>');
  483. }
  484. html.push(
  485. '<li class="page-next"><a href="javascript:void(0)">&gt;</a></li>',
  486. '<li class="page-last"><a href="javascript:void(0)">&gt;&gt;</a></li>',
  487. '</ul>',
  488. '</div>');
  489. this.$pagination.html(html.join(''));
  490. $pageList = this.$pagination.find('.page-list a');
  491. $first = this.$pagination.find('.page-first');
  492. $pre = this.$pagination.find('.page-pre');
  493. $next = this.$pagination.find('.page-next');
  494. $last = this.$pagination.find('.page-last');
  495. $number = this.$pagination.find('.page-number');
  496. if (this.options.pageNumber <= 1) {
  497. $first.addClass('disabled');
  498. $pre.addClass('disabled');
  499. }
  500. if (this.options.pageNumber >= this.totalPages) {
  501. $next.addClass('disabled');
  502. $last.addClass('disabled');
  503. }
  504. $pageList.off('click').on('click', $.proxy(this.onPageListChange, this));
  505. $first.off('click').on('click', $.proxy(this.onPageFirst, this));
  506. $pre.off('click').on('click', $.proxy(this.onPagePre, this));
  507. $next.off('click').on('click', $.proxy(this.onPageNext, this));
  508. $last.off('click').on('click', $.proxy(this.onPageLast, this));
  509. $number.off('click').on('click', $.proxy(this.onPageNumber, this));
  510. };
  511. BootstrapTable.prototype.updatePagination = function () {
  512. this.resetRows();
  513. this.initPagination();
  514. if (this.options.sidePagination === 'server') {
  515. this.initServer();
  516. } else {
  517. this.initBody();
  518. }
  519. };
  520. BootstrapTable.prototype.onPageListChange = function (event) {
  521. var $this = $(event.currentTarget);
  522. $this.parent().addClass('active').siblings().removeClass('active');
  523. this.options.pageSize = +$this.text();
  524. this.$toolbar.find('.page-size').text(this.options.pageSize);
  525. this.updatePagination();
  526. };
  527. BootstrapTable.prototype.onPageFirst = function () {
  528. this.options.pageNumber = 1;
  529. this.updatePagination();
  530. };
  531. BootstrapTable.prototype.onPagePre = function () {
  532. this.options.pageNumber--;
  533. this.updatePagination();
  534. };
  535. BootstrapTable.prototype.onPageNext = function () {
  536. this.options.pageNumber++;
  537. this.updatePagination();
  538. };
  539. BootstrapTable.prototype.onPageLast = function () {
  540. this.options.pageNumber = this.totalPages;
  541. this.updatePagination();
  542. };
  543. BootstrapTable.prototype.onPageNumber = function (event) {
  544. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  545. return;
  546. }
  547. this.options.pageNumber = +$(event.currentTarget).text();
  548. this.updatePagination();
  549. };
  550. BootstrapTable.prototype.initBody = function () {
  551. var that = this,
  552. html = [],
  553. data = this.searchText ? this.data : this.options.data;
  554. this.$body = this.$el.find('tbody');
  555. if (!this.$body.length) {
  556. this.$body = $('<tbody></tbody>').appendTo(this.$el);
  557. }
  558. if (this.options.sidePagination === 'server') {
  559. data = this.data;
  560. }
  561. if (!this.options.pagination || this.options.sidePagination === 'server') {
  562. this.pageFrom = 1;
  563. this.pageTo = data.length;
  564. }
  565. for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
  566. var item = data[i],
  567. style = {},
  568. csses = [];
  569. if (typeof this.options.rowStyle === 'function') {
  570. style = this.options.rowStyle(item, i);
  571. } else if (typeof this.options.rowStyle === 'string') {
  572. style = eval(this.options.rowStyle + '(item, i)');
  573. }
  574. if (style && style.css) {
  575. for (var key in style.css) {
  576. csses.push(key + ': ' + style.css[key]);
  577. }
  578. }
  579. html.push('<tr',
  580. sprintf(' class="%s"', style.classes),
  581. sprintf(' data-index="%s"', i),
  582. '>'
  583. );
  584. if (this.options.cardView) {
  585. html.push(sprintf('<td colspan="%s">', this.header.fields.length));
  586. }
  587. $.each(this.header.fields, function (j, field) {
  588. var text = '',
  589. value = item[field],
  590. type = '',
  591. style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
  592. if (typeof that.header.formatters[j] === 'function') {
  593. value = that.header.formatters[j](value, item, i);
  594. } else if (typeof that.header.formatters[j] === 'string') {
  595. value = eval(that.header.formatters[j] + '(value, item, i)'); // eval ?
  596. }
  597. if (that.options.columns[j].checkbox || that.options.columns[j].radio) {
  598. type = that.options.columns[j].checkbox ? 'checkbox' : type;
  599. type = that.options.columns[j].radio ? 'radio' : type;
  600. text = ['<td class="bs-checkbox">',
  601. '<input' +
  602. sprintf(' data-index="%s"', i) +
  603. sprintf(' name="%s"', that.options.selectItemName) +
  604. sprintf(' type="%s"', type) +
  605. sprintf(' value="%s"', item[that.options.idField]) +
  606. sprintf(' checked="%s"', value ? 'checked' : undefined) + ' />',
  607. '</td>'].join('');
  608. } else {
  609. value = typeof value === 'undefined' ? that.options.undefinedText : value;
  610. text = that.options.cardView ?
  611. ['<div class="card-view">',
  612. sprintf('<span class="title" %s>%s</span>', style,
  613. getPropertyFromOther(that.options.columns, 'field', 'title', field)),
  614. sprintf('<span class="value">%s</span>', value),
  615. '</div>'].join('') :
  616. [sprintf('<td %s>', style),
  617. value,
  618. '</td>'].join('');
  619. }
  620. html.push(text);
  621. });
  622. if (this.options.cardView) {
  623. html.push('</td>');
  624. }
  625. html.push('</tr>');
  626. }
  627. // show no records
  628. if (!html.length) {
  629. html.push('<tr class="no-records-found">',
  630. sprintf('<td colspan="%s">%s</td>', this.header.fields.length, this.options.formatNoMatches()),
  631. '</tr>');
  632. }
  633. this.$body.html(html.join(''));
  634. this.$container.find('.fixed-table-body').scrollTop(0);
  635. this.$body.find('tr').off('click').on('click', function () {
  636. that.trigger('click-row', that.data[$(this).data('index')], $(this));
  637. if (that.options.clickToSelect) {
  638. $(this).find(sprintf('[name="%s"]', that.options.selectItemName)).trigger('click');
  639. }
  640. });
  641. this.$body.find('tr').off('dblclick').on('dblclick', function () {
  642. that.trigger('dbl-click-row', that.data[$(this).data('index')], $(this));
  643. });
  644. this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
  645. this.$selectItem.off('click').on('click', function (event) {
  646. event.stopImmediatePropagation();
  647. var checkAll = that.$selectItem.length === that.$selectItem.filter(':checked').length,
  648. checked = $(this).prop('checked') || $(this).is(':radio'),
  649. row = that.data[$(this).data('index')];
  650. that.$selectAll.add(that.$selectAll_).prop('checked', checkAll);
  651. row[that.header.stateField] = checked;
  652. that.trigger(checked ? 'check' : 'uncheck', row);
  653. if (that.options.singleSelect) {
  654. that.$selectItem.not(this).each(function () {
  655. that.data[$(this).data('index')][that.header.stateField] = false;
  656. });
  657. that.$selectItem.filter(':checked').not(this).prop('checked', false);
  658. }
  659. // $(this).parents('tr')[checked ? 'addClass' : 'removeClass']('selected');
  660. });
  661. $.each(this.header.events, function (i, events) {
  662. if (!events) {
  663. return;
  664. }
  665. if (typeof events === 'string') {
  666. events = eval(events);
  667. }
  668. for (var key in events) {
  669. that.$body.find('tr').each(function () {
  670. var $tr = $(this),
  671. $td = $tr.find('td').eq(i),
  672. index = key.indexOf(' '),
  673. name = key.substring(0, index),
  674. el = key.substring(index + 1),
  675. func = events[key];
  676. $td.find(el).off(name).on(name, function (e) {
  677. var index = $tr.data('index'),
  678. row = that.data[index],
  679. value = row[that.header.fields[i]];
  680. func(e, value, row, index);
  681. });
  682. });
  683. }
  684. });
  685. this.resetView();
  686. };
  687. BootstrapTable.prototype.initServer = function () {
  688. var that = this,
  689. data = {},
  690. params = {
  691. pageSize: this.options.pageSize,
  692. pageNumber: this.options.pageNumber,
  693. searchText: this.searchText,
  694. sortName: this.options.sortName,
  695. sortOrder: this.options.sortOrder
  696. };
  697. if (!this.options.url) {
  698. return;
  699. }
  700. this.$loading.show();
  701. if (this.options.queryParamsType === 'limit') {
  702. params = {
  703. limit: params.pageSize,
  704. offset: params.pageSize * (params.pageNumber - 1),
  705. search: params.searchText,
  706. sort: params.sortName,
  707. order: params.sortOrder
  708. };
  709. }
  710. if (typeof this.options.queryParams === 'function') {
  711. data = this.options.queryParams(params);
  712. } else if (typeof this.options.queryParams === 'string') {
  713. data = eval(this.options.queryParams + '(params)');
  714. }
  715. $.ajax({
  716. type: this.options.method,
  717. url: this.options.url,
  718. data: data,
  719. contentType: this.options.contentType,
  720. dataType: 'json',
  721. success: function (res) {
  722. if (typeof that.options.responseHandler === 'function') {
  723. res = that.options.responseHandler(res);
  724. } else if (typeof that.options.responseHandler === 'string') {
  725. res = eval(that.options.responseHandler + '(res)');
  726. }
  727. var data = res;
  728. if (that.options.sidePagination === 'server') {
  729. that.options.totalRows = res.total;
  730. data = res.rows;
  731. }
  732. that.load(data);
  733. that.trigger('load-success', data);
  734. },
  735. error: function (res) {
  736. that.trigger('load-error', res.status);
  737. },
  738. complete: function () {
  739. that.$loading.hide();
  740. }
  741. });
  742. };
  743. BootstrapTable.prototype.getCaretHtml = function () {
  744. return ['<span class="order' + (this.options.sortOrder === 'desc' ? '' : ' dropup') + '">',
  745. '<span class="caret" style="margin: 10px 5px;"></span>',
  746. '</span>'].join('');
  747. };
  748. BootstrapTable.prototype.updateRows = function (checked) {
  749. var that = this;
  750. this.$selectItem.each(function () {
  751. that.data[$(this).data('index')][that.header.stateField] = checked;
  752. });
  753. };
  754. BootstrapTable.prototype.resetRows = function () {
  755. var that = this;
  756. $.each(this.data, function (i, row) {
  757. that.$selectAll.prop('checked', false);
  758. that.$selectItem.prop('checked', false);
  759. row[that.header.stateField] = false;
  760. });
  761. };
  762. BootstrapTable.prototype.trigger = function (name) {
  763. var args = Array.prototype.slice.call(arguments, 1);
  764. name += '.bs.table';
  765. this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
  766. this.$el.trigger($.Event(name), args);
  767. this.options.onAll(name, args);
  768. this.$el.trigger($.Event('all.bs.table'), [name, args]);
  769. };
  770. BootstrapTable.prototype.resetHeader = function () {
  771. var that = this;
  772. this.$header_ = this.$header.clone(true);
  773. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
  774. this.$el.css('margin-top', -this.$header.height());
  775. this.$container.find('.fixed-table-header')
  776. .css({
  777. 'height': '37px',
  778. 'border-bottom': '1px solid #dddddd'
  779. })
  780. .find('table').css('width', this.$el.css('width'))
  781. .html('').attr('class', this.$el.attr('class'))
  782. .append(this.$header_);
  783. this.$body.find('tr:first-child:not(.no-records-found) > *').each(function(i) {
  784. that.$header_.find('div.fht-cell').eq(i).width($(this).innerWidth());
  785. });
  786. };
  787. // PUBLIC FUNCTION DEFINITION
  788. // =======================
  789. BootstrapTable.prototype.resetView = function (params) {
  790. var that = this,
  791. header = this.header;
  792. if (params && params.height) {
  793. this.options.height = params.height;
  794. }
  795. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  796. this.$selectItem.length === this.$selectItem.filter(':checked').length);
  797. if (this.options.height) {
  798. var toolbarHeight = +this.$toolbar.children().outerHeight(true),
  799. paginationHeight = +this.$pagination.children().outerHeight(true),
  800. height = this.options.height - toolbarHeight - paginationHeight;
  801. this.$container.find('.fixed-table-container').css('height', height + 'px');
  802. }
  803. if (this.options.cardView) {
  804. return;
  805. }
  806. if (this.options.showHeader && this.options.height) {
  807. this.resetHeader();
  808. }
  809. if (this.options.height && this.options.showHeader) {
  810. this.$container.find('.fixed-table-container').css('padding-bottom', '38px');
  811. }
  812. };
  813. BootstrapTable.prototype.load = function (data) {
  814. this.initData(data);
  815. this.initPagination();
  816. this.initBody();
  817. };
  818. BootstrapTable.prototype.append = function (data) {
  819. this.initData(data, true);
  820. this.initBody();
  821. };
  822. BootstrapTable.prototype.mergeCells = function (options) {
  823. var row = options.index,
  824. col = $.inArray(options.field, this.header.fields),
  825. rowspan = options.rowspan || 1,
  826. colspan = options.colspan || 1,
  827. i, j,
  828. $tr = this.$body.find('tr'),
  829. $td = $tr.eq(row).find('td').eq(col);
  830. if (row < 0 || col < 0 || row >= this.data.length) {
  831. return;
  832. }
  833. for (i = row; i < row + rowspan; i++) {
  834. for (j = col; j < col + colspan; j++) {
  835. $tr.eq(i).find('td').eq(j).hide();
  836. }
  837. }
  838. $td.attr('rowspan', rowspan).attr('colspan', colspan).show();
  839. };
  840. BootstrapTable.prototype.getSelections = function () {
  841. var that = this;
  842. return $.grep(this.data, function (row) {
  843. return row[that.header.stateField];
  844. });
  845. };
  846. BootstrapTable.prototype.checkAll = function () {
  847. this.$selectAll.add(this.$selectAll_).prop('checked', true);
  848. this.$selectItem.prop('checked', true);
  849. this.updateRows(true);
  850. this.trigger('check-all');
  851. };
  852. BootstrapTable.prototype.uncheckAll = function () {
  853. this.$selectAll.add(this.$selectAll_).prop('checked', false);
  854. this.$selectItem.prop('checked', false);
  855. this.updateRows(false);
  856. this.trigger('uncheck-all');
  857. };
  858. BootstrapTable.prototype.destroy = function () {
  859. this.$el.insertBefore(this.$container);
  860. $(this.options.toolbar).insertBefore(this.$el);
  861. this.$container.next().remove();
  862. this.$container.remove();
  863. this.$el.html(this.$el_.html())
  864. .attr('class', this.$el_.attr('class') || ''); // reset the class
  865. };
  866. BootstrapTable.prototype.showLoading = function () {
  867. this.$loading.show();
  868. };
  869. BootstrapTable.prototype.hideLoading = function () {
  870. this.$loading.hide();
  871. };
  872. BootstrapTable.prototype.refresh = function () {
  873. this.initServer();
  874. };
  875. // BOOTSTRAP TABLE PLUGIN DEFINITION
  876. // =======================
  877. $.fn.bootstrapTable = function (option, _relatedTarget) {
  878. var allowedMethods = [
  879. 'getSelections',
  880. 'load', 'append', 'mergeCells',
  881. 'checkAll', 'uncheckAll',
  882. 'destroy', 'resetView',
  883. 'showLoading', 'hideLoading',
  884. 'refresh'
  885. ],
  886. value;
  887. this.each(function () {
  888. var $this = $(this),
  889. data = $this.data('bootstrap.table'),
  890. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(), typeof option === 'object' && option);
  891. if (!data) {
  892. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  893. }
  894. if (typeof option === 'string') {
  895. if ($.inArray(option, allowedMethods) < 0) {
  896. throw "Unknown method: " + option;
  897. }
  898. value = data[option](_relatedTarget);
  899. if (option === 'destroy') {
  900. $this.removeData('bootstrap.table');
  901. }
  902. }
  903. });
  904. return typeof value === 'undefined' ? this : value;
  905. };
  906. $.fn.bootstrapTable.Constructor = BootstrapTable;
  907. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
  908. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
  909. // BOOTSTRAP TABLE INIT
  910. // =======================
  911. $(function () {
  912. $('[data-toggle="table"]').bootstrapTable();
  913. });
  914. }(jQuery);