bootstrap-table.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.0.2
  4. */
  5. !function ($) {
  6. 'use strict';
  7. // TOOLS DEFINITION
  8. // ======================
  9. // it only does '%s', and return '' when arguments are undefined
  10. var sprintf = function(str) {
  11. var args = arguments,
  12. flag = true,
  13. i = 1;
  14. str = str.replace(/%s/g, function() {
  15. var arg = args[i++];
  16. if (typeof arg === 'undefined') {
  17. flag = false;
  18. return '';
  19. }
  20. return arg;
  21. });
  22. if (flag) {
  23. return str;
  24. }
  25. return '';
  26. };
  27. // BOOTSTRAP TABLE CLASS DEFINITION
  28. // ======================
  29. var BootstrapTable = function(el, options) {
  30. this.options = options;
  31. this.$el = $(el);
  32. this.$el_ = this.$el.clone();
  33. this.init();
  34. };
  35. BootstrapTable.DEFAULTS = {
  36. classes: 'table table-hover',
  37. height: undefined,
  38. undefinedText: '-',
  39. sortName: undefined,
  40. sortOrder: 'asc',
  41. striped: false,
  42. columns: [],
  43. data: [],
  44. method: 'get',
  45. url: undefined,
  46. queryParams: {},
  47. pagination: false,
  48. sidePagination: 'client', // client or server
  49. totalRows: 0, // server side need to set
  50. pageNumber: 1,
  51. pageSize: 10,
  52. pageList: [10, 25, 50, 100],
  53. search: false,
  54. selectItemName: 'btSelectItem',
  55. hideHeader: false,
  56. formatRecordsPerPage: function(pageNumber) {
  57. return sprintf('%s records per page', pageNumber);
  58. },
  59. formatShowingRows: function(pageFrom, pageTo, totalRows) {
  60. return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows);
  61. },
  62. formatSearch: function() {
  63. return 'Search';
  64. },
  65. onClickRow: function(item) {return false;},
  66. onSort: function(name, order) {return false;},
  67. onCheck: function(row) {return false;},
  68. onUncheck: function(row) {return false;},
  69. onCheckAll: function(rows) {return false;},
  70. onUncheckAll: function(rows) {return false;}
  71. };
  72. BootstrapTable.prototype.init = function() {
  73. this.initContainer();
  74. this.initHeader();
  75. this.initData();
  76. this.initToolbar();
  77. this.initPagination();
  78. this.initBody();
  79. this.initServer();
  80. };
  81. BootstrapTable.prototype.initContainer = function() {
  82. this.$container = $([
  83. '<div>',
  84. '<div class="fixed-table-toolbar"></div>',
  85. '<div class="fixed-table-container">',
  86. '<div class="fixed-table-header"></div>',
  87. '<div class="fixed-table-body"></div>',
  88. '<div class="fixed-table-pagination"></div>',
  89. '</div>',
  90. '</div>'].join(''));
  91. this.$container.insertAfter(this.$el);
  92. this.$container.find('.fixed-table-body').append(this.$el);
  93. this.$container.after('<div class="clearfix"></div>');
  94. if (this.options.height) {
  95. this.$container.find('.fixed-table-container').css('height', this.options.height + 'px');
  96. }
  97. this.$el.addClass(this.options.classes);
  98. if (this.options.striped) {
  99. this.$el.addClass('table-striped');
  100. }
  101. };
  102. BootstrapTable.prototype.initHeader = function() {
  103. var that = this,
  104. columns = [],
  105. html = [];
  106. this.$header = this.$el.find('thead');
  107. if (!this.$header.length) {
  108. this.$header = $('<thead></thead>').appendTo(this.$el);
  109. }
  110. if (!this.$header.find('tr').length) {
  111. this.$header.append('<tr></tr>');
  112. }
  113. this.$header.find('th').each(function() {
  114. var column = $.extend({}, {
  115. title: $(this).text()
  116. }, $(this).data());
  117. columns.push(column);
  118. });
  119. this.options.columns = $.extend(columns, this.options.columns);
  120. this.header = {
  121. fields: [],
  122. styles: [],
  123. formatters: [],
  124. sorters: []
  125. };
  126. $.each(this.options.columns, function(i, column) {
  127. var text = '',
  128. style = sprintf('text-align: %s; ', column.align) + sprintf('vertical-align: %s; ', column.valign),
  129. order = that.options.sortOrder || column.order || 'asc';
  130. that.header.fields.push(column.field);
  131. that.header.styles.push(style);
  132. that.header.formatters.push(column.formatter);
  133. that.header.sorters.push(column.sorter);
  134. style = sprintf('width: %spx; ', column.checkbox || column.radio ? 36 : column.width);
  135. style += column.sortable ? 'cursor: pointer; ' : '';
  136. html.push('<th' + sprintf(' style="%s"', style) + '>');
  137. html.push('<div class="th-inner">');
  138. text = column.title;
  139. if (that.options.sortName === column.field && column.sortable) {
  140. text += that.getCaretHtml();
  141. }
  142. if (column.checkbox) {
  143. text = '<input name="btSelectAll" type="checkbox" class="checkbox" />';
  144. that.header.stateField = column.field;
  145. }
  146. if (column.radio) {
  147. text = '';
  148. that.header.stateField = column.field;
  149. }
  150. html.push(text);
  151. html.push('</div>');
  152. html.push('</th>');
  153. });
  154. this.$header.find('tr').html(html.join(''));
  155. this.$header.find('th').each(function(i) {
  156. $(this).data(columns[i]);
  157. if (columns[i].sortable) {
  158. $(this).click($.proxy(that.onSort, that));
  159. }
  160. });
  161. if (this.options.hideHeader) {
  162. this.$header.hide();
  163. this.$container.find('.fixed-table-header').css('border-bottom', 'none');
  164. this.$container.find('.fixed-table-container').css('padding-top', 0);
  165. }
  166. this.$selectAll = this.$header.find('[name="btSelectAll"]');
  167. this.$selectAll.off('click').on('click', function() {
  168. var checked = $(this).prop('checked');
  169. that[checked ? 'checkAll' : 'uncheckAll']();
  170. });
  171. };
  172. BootstrapTable.prototype.initData = function(data, append) {
  173. if (append) {
  174. this.data = this.data.concat(data);
  175. } else {
  176. this.data = data || this.options.data;
  177. }
  178. this.initSort();
  179. };
  180. BootstrapTable.prototype.initSort = function() {
  181. var name = this.options.sortName,
  182. order = this.options.sortOrder === 'desc' ? -1 : 1,
  183. index = $.inArray(this.options.sortName, this.header.fields);
  184. if (index !== -1) {
  185. var sorter = this.header.sorters[index];
  186. this.data.sort(function(a, b) {
  187. if (typeof sorter === 'function') {
  188. return order * sorter(a[name], b[name]);
  189. }
  190. if (typeof sorter === 'string') {
  191. return order * eval(sorter + '(a[name], b[name])'); // eval ?
  192. }
  193. if (a[name] === b[name]) {
  194. return 0;
  195. }
  196. if (a[name] < b[name]) {
  197. return order * -1;
  198. }
  199. return order;
  200. });
  201. }
  202. };
  203. BootstrapTable.prototype.onSort = function(event) {
  204. var $this = $(event.currentTarget);
  205. this.$header.find('span.order').remove();
  206. this.options.sortName = $this.data('field');
  207. this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
  208. this.options.onSort(this.options.sortName, this.options.sortOrder);
  209. $this.data('order', this.options.sortOrder);
  210. $this.find('.th-inner').append(this.getCaretHtml());
  211. this.initSort();
  212. this.initBody();
  213. };
  214. BootstrapTable.prototype.initToolbar = function() {
  215. var that = this,
  216. html = [],
  217. $pageList,
  218. $search;
  219. this.$toolbar = this.$container.find('.fixed-table-toolbar');
  220. if (this.options.pagination) {
  221. html = [];
  222. html.push('<div class="page-list">');
  223. var pageNumber = [
  224. '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">',
  225. '<span class="page-size">',
  226. this.options.pageSize,
  227. '</span>',
  228. ' <span class="caret"></span>',
  229. '</button>',
  230. '<ul class="dropdown-menu" role="menu">'];
  231. $.each(this.options.pageList, function(i, page) {
  232. var active = page === that.options.pageSize ? ' class="active"' : '';
  233. pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page));
  234. });
  235. pageNumber.push('</ul>');
  236. html.push(this.options.formatRecordsPerPage(pageNumber.join('')));
  237. html.push('</div>');
  238. this.$toolbar.append(html.join(''));
  239. $pageList = this.$toolbar.find('.page-list a');
  240. $pageList.off('click').on('click', $.proxy(this.onPageListChange, this));
  241. }
  242. if (this.options.search) {
  243. html = [];
  244. html.push(
  245. '<div class="pull-right search">',
  246. sprintf('<input class="form-control" type="text" placeholder="%s">',
  247. this.options.formatSearch()),
  248. '</div>');
  249. this.$toolbar.append(html.join(''));
  250. $search = this.$toolbar.find('.search input');
  251. $search.off('keyup').on('keyup', $.proxy(this.onSearch, this));
  252. }
  253. };
  254. BootstrapTable.prototype.onSearch = function(event) {
  255. var that = this;
  256. this.searchText = $(event.currentTarget).val();
  257. this.searchData = $.grep(this.data, function(item) {
  258. for (var key in item) {
  259. if (typeof item[key] === 'string' && item[key].indexOf(that.searchText) !== -1) {
  260. return true;
  261. }
  262. }
  263. return false;
  264. });
  265. this.resetRows();
  266. this.initPagination();
  267. this.initBody();
  268. };
  269. BootstrapTable.prototype.initPagination = function() {
  270. if (!this.options.pagination) {
  271. return;
  272. }
  273. var that = this,
  274. html = [],
  275. i, from, to,
  276. $first, $pre,
  277. $next, $last,
  278. $number,
  279. data = this.searchText ? this.searchData : this.data;
  280. this.$pagination = this.$container.find('.fixed-table-pagination');
  281. if (this.options.sidePagination === 'client') {
  282. this.options.totalRows = data.length;
  283. }
  284. this.totalPages = 0;
  285. if (this.options.totalRows) {
  286. this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
  287. }
  288. if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
  289. this.options.pageNumber = this.totalPages;
  290. }
  291. this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
  292. this.pageTo = this.options.pageNumber * this.options.pageSize;
  293. if (this.pageTo > this.options.totalRows) {
  294. this.pageTo = this.options.totalRows;
  295. }
  296. html.push(
  297. '<div class="pull-left pagination">',
  298. '<div class="pagination-info">',
  299. this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
  300. '</div>',
  301. '</div>',
  302. '<div class="pull-right">',
  303. '<ul class="pagination">',
  304. '<li class="page-first"><a href="javascript:void(0)">&lt;&lt;</a></li>',
  305. '<li class="page-pre"><a href="javascript:void(0)">&lt;</a></li>');
  306. if (this.totalPages < 5) {
  307. from = 1;
  308. to = this.totalPages;
  309. } else {
  310. from = this.options.pageNumber - 2;
  311. to = from + 4;
  312. if (from < 1) {
  313. from = 1;
  314. to = 5;
  315. }
  316. if (to > this.totalPages) {
  317. to = this.totalPages;
  318. from = to - 4;
  319. }
  320. }
  321. for (i = from; i <= to; i++) {
  322. html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
  323. '<a href="javascript:void(0)">', i ,'</a>',
  324. '</li>');
  325. }
  326. html.push(
  327. '<li class="page-next"><a href="javascript:void(0)">&gt;</a></li>',
  328. '<li class="page-last"><a href="javascript:void(0)">&gt;&gt;</a></li>',
  329. '</ul>',
  330. '</div>');
  331. this.$pagination.html(html.join(''));
  332. $first = this.$pagination.find('.page-first');
  333. $pre = this.$pagination.find('.page-pre');
  334. $next = this.$pagination.find('.page-next');
  335. $last = this.$pagination.find('.page-last');
  336. $number = this.$pagination.find('.page-number');
  337. if (this.options.pageNumber <= 1) {
  338. $first.addClass('disabled');
  339. $pre.addClass('disabled');
  340. }
  341. if (this.options.pageNumber >= this.totalPages) {
  342. $next.addClass('disabled');
  343. $last.addClass('disabled');
  344. }
  345. $first.off('click').on('click', $.proxy(this.onPageFirst, this));
  346. $pre.off('click').on('click', $.proxy(this.onPagePre, this));
  347. $next.off('click').on('click', $.proxy(this.onPageNext, this));
  348. $last.off('click').on('click', $.proxy(this.onPageLast, this));
  349. $number.off('click').on('click', $.proxy(this.onPageNumber, this));
  350. };
  351. BootstrapTable.prototype.onPageListChange = function(event) {
  352. var $this = $(event.currentTarget);
  353. $this.parent().addClass('active').siblings().removeClass('active');
  354. this.options.pageSize = +$this.text();
  355. this.$toolbar.find('.page-size').text(this.options.pageSize);
  356. this.resetRows();
  357. this.initPagination();
  358. this.initBody();
  359. };
  360. BootstrapTable.prototype.onPageFirst = function() {
  361. this.options.pageNumber = 1;
  362. this.resetRows();
  363. this.initPagination();
  364. this.initBody();
  365. };
  366. BootstrapTable.prototype.onPagePre = function() {
  367. this.options.pageNumber--;
  368. this.resetRows();
  369. this.initPagination();
  370. this.initBody();
  371. };
  372. BootstrapTable.prototype.onPageNext = function() {
  373. this.options.pageNumber++;
  374. this.resetRows();
  375. this.initPagination();
  376. this.initBody();
  377. };
  378. BootstrapTable.prototype.onPageLast = function() {
  379. this.options.pageNumber = this.totalPages;
  380. this.resetRows();
  381. this.initPagination();
  382. this.initBody();
  383. };
  384. BootstrapTable.prototype.onPageNumber = function(event) {
  385. this.options.pageNumber = +$(event.currentTarget).text();
  386. this.resetRows();
  387. this.initPagination();
  388. this.initBody();
  389. };
  390. BootstrapTable.prototype.initBody = function() {
  391. var that = this,
  392. html = [],
  393. data = this.searchText ? this.searchData : this.data;;
  394. this.$body = this.$el.find('tbody');
  395. if (!this.$body.length) {
  396. this.$body = $('<tbody></tbody>').appendTo(this.$el);
  397. }
  398. if (!this.options.pagination) {
  399. this.pageFrom = 1;
  400. this.pageTo = data.length;
  401. }
  402. for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
  403. var item = data[i];
  404. html.push('<tr' + ' data-index="' + i + '">');
  405. $.each(that.header.fields, function(j, field) {
  406. var text = '',
  407. value = item[field],
  408. type = '';
  409. if (typeof that.header.formatters[j] === 'function') {
  410. value = that.header.formatters[j](value, item);
  411. } else if (typeof that.header.formatters[j] === 'string') {
  412. value = eval(that.header.formatters[j] + '(value, item)'); // eval ?
  413. }
  414. text = ['<td' + sprintf(' style="%s"', that.header.styles[j]) + '>',
  415. typeof value === 'undefined' ? that.options.undefinedText : value,
  416. '</td>'].join('');
  417. if (that.options.columns[j].checkbox || that.options.columns[j].radio) {
  418. type = that.options.columns[j].checkbox ? 'checkbox' : type;
  419. type = that.options.columns[j].radio ? 'radio' : type;
  420. text = ['<td>',
  421. '<input class="checkbox"' +
  422. sprintf(' data-index="%s"', i) +
  423. sprintf(' name="%s"', that.options.selectItemName) +
  424. sprintf(' type="%s"', type) +
  425. sprintf(' checked="%s"', value ? 'checked' : undefined) + ' />',
  426. '</td>'].join('');
  427. }
  428. html.push(text);
  429. });
  430. html.push('</tr>');
  431. }
  432. // show no records
  433. if (!html.length) {
  434. html.push('<tr class="no-records-found">',
  435. sprintf('<td colspan="%s">No matching records found</td>', this.header.fields.length),
  436. '</tr>');
  437. }
  438. this.$body.html(html.join(''));
  439. this.$body.find('tr').off('click').on('click', function() {
  440. that.options.onClickRow(that.data[$(this).data('index')]);
  441. });
  442. this.$selectItem = this.$body.find('[name="btSelectItem"]');
  443. this.$selectItem.off('click').on('click', function() {
  444. var checkAll = that.$selectItem.length === that.$selectItem.filter(':checked').length;
  445. that.$selectAll.prop('checked', checkAll);
  446. that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked');
  447. });
  448. this.resetView();
  449. };
  450. BootstrapTable.prototype.initServer = function() {
  451. var that = this;
  452. if (!this.options.url) {
  453. return;
  454. }
  455. $.ajax({
  456. type: this.options.method,
  457. url: this.options.url,
  458. data: this.options.queryParams,
  459. contentType: 'application/json',
  460. dataType: 'json',
  461. success: function(data) {
  462. that.load(data);
  463. }
  464. });
  465. };
  466. BootstrapTable.prototype.getCaretHtml = function() {
  467. return ['<span class="order' + (this.options.sortOrder === 'desc' ? '' : ' dropup') + '">',
  468. '<span class="caret" style="margin: 10px 5px;"></span>',
  469. '</span>'].join('');
  470. };
  471. BootstrapTable.prototype.updateRows = function(checked) {
  472. var that = this;
  473. this.$selectItem.each(function() {
  474. that.data[$(this).data('index')][that.header.stateField] = checked;
  475. });
  476. };
  477. BootstrapTable.prototype.resetRows = function() {
  478. var that = this;
  479. $.each(this.data, function(i, row) {
  480. that.$selectAll.prop('checked', false);
  481. that.$selectItem.prop('checked', false);
  482. row[that.header.stateField] = false;
  483. });
  484. };
  485. // PUBLIC FUNCTION DEFINITION
  486. // =======================
  487. BootstrapTable.prototype.resetView = function() {
  488. var header = this.header;
  489. this.$header.find('.th-inner').each(function(i) {
  490. $(this).attr('style', header.styles[i])
  491. .css('width', ($(this).parent().width()) + 'px'); // padding: 8px
  492. });
  493. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  494. this.$selectItem.length === this.$selectItem.filter(':checked').length);
  495. };
  496. BootstrapTable.prototype.load = function(data) {
  497. this.initData(data);
  498. this.initPagination();
  499. this.initBody();
  500. };
  501. BootstrapTable.prototype.append = function(data) {
  502. this.initData(data, true);
  503. this.initBody();
  504. };
  505. BootstrapTable.prototype.mergeCells = function(options) {
  506. var row = options.index,
  507. col = $.inArray(options.field, this.header.fields),
  508. rowspan = options.rowspan || 1,
  509. colspan = options.colspan || 1,
  510. i, j,
  511. $tr = this.$body.find('tr'),
  512. $td = $tr.eq(row).find('td').eq(col);
  513. if (row < 0 || col < 0 || row >= this.data.length) {
  514. return;
  515. }
  516. for (i = row; i < row + rowspan; i++) {
  517. for (j = col; j < col + colspan; j++) {
  518. $tr.eq(i).find('td').eq(j).hide();
  519. }
  520. }
  521. $td.attr('rowspan', rowspan).attr('colspan', colspan).show();
  522. };
  523. BootstrapTable.prototype.getSelections = function() {
  524. var that = this;
  525. return $.grep(this.data, function(row) {
  526. return row[that.header.stateField];
  527. });
  528. };
  529. BootstrapTable.prototype.checkAll = function() {
  530. this.$selectAll.prop('checked', true);
  531. this.$selectItem.prop('checked', true);
  532. this.updateRows(true);
  533. };
  534. BootstrapTable.prototype.uncheckAll = function() {
  535. this.$selectAll.prop('checked', false);
  536. this.$selectItem.prop('checked', false);
  537. this.updateRows(false);
  538. };
  539. BootstrapTable.prototype.destroy = function() {
  540. this.$container.next().remove();
  541. this.$container.replaceWith(this.$el_);
  542. return this.$el_;
  543. };
  544. // BOOTSTRAP TABLE PLUGIN DEFINITION
  545. // =======================
  546. $.fn.bootstrapTable = function(option, _relatedTarget) {
  547. var allowedMethods = [
  548. 'getSelections',
  549. 'load', 'append', 'mergeCells',
  550. 'checkAll', 'uncheckAll',
  551. 'destroy', 'resetView'
  552. ],
  553. value;
  554. this.each(function() {
  555. var $this = $(this),
  556. data = $this.data('bootstrap.table'),
  557. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(), typeof option === 'object' && option);
  558. if (!data) {
  559. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  560. }
  561. if (typeof option === 'string') {
  562. if ($.inArray(option, allowedMethods) < 0) {
  563. throw "Unknown method: " + option;
  564. }
  565. value = data[option](_relatedTarget);
  566. }
  567. });
  568. return value ? value : this;
  569. };
  570. $.fn.bootstrapTable.Constructor = BootstrapTable;
  571. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
  572. // BOOTSTRAP TABLE INIT
  573. // =======================
  574. $(function() {
  575. $('[data-toggle="table"]').bootstrapTable();
  576. });
  577. }(jQuery);