bootstrap-table.js 21 KB

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