bootstrap-table.js 33 KB

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