bootstrap-table.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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.init();
  33. };
  34. BootstrapTable.DEFAULTS = {
  35. classes: 'table table-hover',
  36. height: undefined,
  37. undefinedText: '-',
  38. sortName: undefined,
  39. sortOrder: 'asc',
  40. striped: false,
  41. columns: [],
  42. data: [],
  43. method: 'get',
  44. url: undefined,
  45. queryParams: {},
  46. pagination: false,
  47. sidePagination: 'client', // client or server
  48. totalRows: 0, // server side need to set
  49. pageNumber: 1,
  50. pageSize: 10,
  51. pageList: [10, 20, 30, 40, 50],
  52. onClickRow: function(item) {return false;},
  53. onSort: function(name, order) {return false;},
  54. onCheck: function(row) {return false;},
  55. onUncheck: function(row) {return false;},
  56. onCheckAll: function(rows) {return false;},
  57. onUncheckAll: function(rows) {return false;}
  58. };
  59. BootstrapTable.prototype.init = function() {
  60. this.initContainer();
  61. this.initHeader();
  62. this.initData();
  63. this.initPagination();
  64. this.initBody();
  65. this.initServer();
  66. };
  67. BootstrapTable.prototype.initContainer = function() {
  68. this.$container = $([
  69. '<div class="fixed-table-container">',
  70. '<div class="fixed-table-header"></div>',
  71. '<div class="fixed-table-body"></div>',
  72. '<div class="fixed-table-pagination"></div>',
  73. '</div>'].join(''));
  74. this.$container.insertAfter(this.$el);
  75. this.$container.find('.fixed-table-body').append(this.$el);
  76. this.$container.after('<div class="clearfix"></div>');
  77. if (this.options.height) {
  78. this.$container.css('height', this.options.height + 'px');
  79. }
  80. this.$el.addClass(this.options.classes);
  81. if (this.options.striped) {
  82. this.$el.addClass('table-striped');
  83. }
  84. };
  85. BootstrapTable.prototype.initHeader = function() {
  86. var that = this,
  87. columns = [],
  88. html = [];
  89. this.$header = this.$el.find('thead');
  90. if (!this.$header.length) {
  91. this.$header = $('<thead></thead>').appendTo(this.$el);
  92. }
  93. if (!this.$header.find('tr').length) {
  94. this.$header.append('<tr></tr>');
  95. }
  96. this.$header.find('th').each(function() {
  97. var column = $.extend({}, {
  98. title: $(this).text()
  99. }, $(this).data());
  100. columns.push(column);
  101. });
  102. this.options.columns = $.extend(columns, this.options.columns);
  103. this.header = {
  104. fields: [],
  105. styles: [],
  106. formatters: [],
  107. sorters: []
  108. };
  109. $.each(this.options.columns, function(i, column) {
  110. var text = '',
  111. style = sprintf('text-align: %s; ', column.align) + sprintf('vertical-align: %s; ', column.valign),
  112. order = that.options.sortOrder || column.order || 'asc';
  113. that.header.fields.push(column.field);
  114. that.header.styles.push(style);
  115. that.header.formatters.push(column.formatter);
  116. that.header.sorters.push(column.sorter);
  117. style = sprintf('width: %spx; ', column.checkbox || column.radio ? 36 : column.width);
  118. style += column.sortable ? 'cursor: pointer; ' : '';
  119. html.push('<th' + sprintf(' style="%s"', style) + '>');
  120. html.push('<div class="th-inner">');
  121. text = column.title;
  122. if (that.options.sortName === column.field && column.sortable) {
  123. text += that.getCaretHtml();
  124. }
  125. if (column.checkbox) {
  126. text = '<input name="btSelectAll" type="checkbox" class="checkbox" />';
  127. that.header.stateField = column.field;
  128. }
  129. if (column.radio) {
  130. text = '';
  131. that.header.stateField = column.field;
  132. }
  133. html.push(text);
  134. html.push('</div>');
  135. html.push('</th>');
  136. });
  137. this.$header.find('tr').html(html.join(''));
  138. this.$header.find('th').each(function(i) {
  139. $(this).data(columns[i]);
  140. if (columns[i].sortable) {
  141. $(this).click($.proxy(that.onSort, that));
  142. }
  143. });
  144. this.$selectAll = this.$header.find('[name="btSelectAll"]');
  145. this.$selectAll.off('click').on('click', function() {
  146. var checked = $(this).prop('checked');
  147. that[checked ? 'checkAll' : 'uncheckAll']();
  148. });
  149. };
  150. BootstrapTable.prototype.initData = function(data, append) {
  151. if (append) {
  152. this.data = this.data.concat(data);
  153. } else {
  154. this.data = data || this.options.data;
  155. }
  156. this.initSort();
  157. };
  158. BootstrapTable.prototype.initSort = function() {
  159. var name = this.options.sortName,
  160. order = this.options.sortOrder === 'desc' ? -1 : 1,
  161. index = $.inArray(this.options.sortName, this.header.fields);
  162. if (index !== -1) {
  163. var sorter = this.header.sorters[index];
  164. this.data.sort(function(a, b) {
  165. if (typeof sorter === 'function') {
  166. return order * sorter(a[name], b[name]);
  167. }
  168. if (a[name] === b[name]) {
  169. return 0;
  170. }
  171. if (a[name] < b[name]) {
  172. return order * -1;
  173. }
  174. return order;
  175. });
  176. }
  177. };
  178. BootstrapTable.prototype.onSort = function(event) {
  179. var $this = $(event.currentTarget);
  180. this.$header.find('span.order').remove();
  181. this.options.sortName = $this.data('field');
  182. this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
  183. this.options.onSort(this.options.sortName, this.options.sortOrder);
  184. $this.data('order', this.options.sortOrder);
  185. $this.find('.th-inner').append(this.getCaretHtml());
  186. this.initSort();
  187. this.initBody();
  188. };
  189. BootstrapTable.prototype.initPagination = function() {
  190. if (!this.options.pagination) {
  191. return;
  192. }
  193. this.$pagination = this.$container.find('.fixed-table-pagination');
  194. if (this.options.sidePagination === 'client') {
  195. this.options.totalRows = this.data.length;
  196. }
  197. this.totalPages = 0;
  198. if (this.options.totalRows) {
  199. this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
  200. }
  201. this.updatePagination();
  202. };
  203. BootstrapTable.prototype.updatePagination = function() {
  204. var html = [],
  205. i, from, to,
  206. $first, $pre,
  207. $next, $last,
  208. $number;
  209. this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
  210. this.pageTo = this.options.pageNumber * this.options.pageSize;
  211. if (this.pageTo > this.options.totalRows) {
  212. this.pageTo = this.options.totalRows;
  213. }
  214. html.push(
  215. '<div class="pull-left pagination">',
  216. '<div class="pagination-info">',
  217. sprintf('Showing %s to %s of %s rows', this.pageFrom, this.pageTo, this.options.totalRows),
  218. '</div>',
  219. '</div>',
  220. '<div class="pull-right">',
  221. '<ul class="pagination">',
  222. '<li class="page-first"><a href="javascript:void(0)">&lt;&lt;</a></li>',
  223. '<li class="page-pre"><a href="javascript:void(0)">&lt;</a></li>');
  224. if (this.totalPages < 5) {
  225. from = 1;
  226. to = this.totalPages;
  227. } else {
  228. from = this.options.pageNumber - 2;
  229. to = from + 4;
  230. if (from < 1) {
  231. from = 1;
  232. to = 5;
  233. }
  234. if (to > this.totalPages) {
  235. to = this.totalPages;
  236. from = to - 4;
  237. }
  238. }
  239. for (i = from; i <= to; i++) {
  240. html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
  241. '<a href="javascript:void(0)">', i ,'</a>',
  242. '</li>');
  243. }
  244. html.push(
  245. '<li class="page-next"><a href="javascript:void(0)">&gt;</a></li>',
  246. '<li class="page-last"><a href="javascript:void(0)">&gt;&gt;</a></li>',
  247. '</ul>',
  248. '</div>')
  249. this.$pagination.html(html.join(''));
  250. $first = this.$pagination.find('.page-first');
  251. $pre = this.$pagination.find('.page-pre');
  252. $next = this.$pagination.find('.page-next');
  253. $last = this.$pagination.find('.page-last');
  254. $number = this.$pagination.find('.page-number');
  255. if (this.options.pageNumber <= 1) {
  256. $first.addClass('disabled');
  257. $pre.addClass('disabled');
  258. }
  259. if (this.options.pageNumber >= this.totalPages) {
  260. $next.addClass('disabled');
  261. $last.addClass('disabled');
  262. }
  263. $first.off('click').on('click', $.proxy(this.onPageFirst, this));
  264. $pre.off('click').on('click', $.proxy(this.onPagePre, this));
  265. $next.off('click').on('click', $.proxy(this.onPageNext, this));
  266. $last.off('click').on('click', $.proxy(this.onPageLast, this));
  267. $number.off('click').on('click', $.proxy(this.onPageNumber, this));
  268. };
  269. BootstrapTable.prototype.onPageFirst = function() {
  270. this.options.pageNumber = 1;
  271. this.updatePagination();
  272. this.initBody();
  273. };
  274. BootstrapTable.prototype.onPagePre = function() {
  275. this.options.pageNumber--;
  276. this.updatePagination();
  277. this.initBody();
  278. };
  279. BootstrapTable.prototype.onPageNext = function() {
  280. this.options.pageNumber++;
  281. this.updatePagination();
  282. this.initBody();
  283. };
  284. BootstrapTable.prototype.onPageLast = function() {
  285. this.options.pageNumber = this.totalPages;
  286. this.updatePagination();
  287. this.initBody();
  288. };
  289. BootstrapTable.prototype.onPageNumber = function(event) {
  290. this.options.pageNumber = +$(event.currentTarget).text();
  291. this.updatePagination();
  292. this.initBody();
  293. };
  294. BootstrapTable.prototype.initBody = function() {
  295. var that = this,
  296. html = [];
  297. this.$body = this.$el.find('tbody');
  298. if (!this.$body.length) {
  299. this.$body = $('<tbody></tbody>').appendTo(this.$el);
  300. }
  301. if (!this.options.pagination) {
  302. this.pageFrom = 1;
  303. this.pageTo = this.data.length;
  304. }
  305. for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
  306. var item = this.data[i];
  307. html.push('<tr' + ' data-index="' + i + '">');
  308. $.each(that.header.fields, function(j, field) {
  309. var text = '',
  310. value = item[field],
  311. type = '';
  312. if (typeof that.header.formatters[j] === 'function') {
  313. value = that.header.formatters[j](value, item);
  314. }
  315. text = ['<td' + sprintf(' style="%s"', that.header.styles[j]) + '>',
  316. typeof value === 'undefined' ? that.options.undefinedText : value,
  317. '</td>'].join('');
  318. if (that.options.columns[j].checkbox || that.options.columns[j].radio) {
  319. type = that.options.columns[j].checkbox ? 'checkbox' : type;
  320. type = that.options.columns[j].radio ? 'radio' : type;
  321. text = ['<td>',
  322. '<input name="btSelectItem" class="checkbox" data-index="' + i + '"' +
  323. sprintf(' type="%s"', type) +
  324. sprintf(' checked="%s"', value ? 'checked' : undefined) + ' />',
  325. '</td>'].join('');
  326. }
  327. html.push(text);
  328. });
  329. html.push('</tr>');
  330. }
  331. this.$body.html(html.join(''));
  332. this.$body.find('tr').off('click').on('click', function() {
  333. that.options.onClickRow(that.data[$(this).data('index')]);
  334. });
  335. this.$selectItem = this.$body.find('[name="btSelectItem"]');
  336. this.$selectItem.off('click').on('click', function() {
  337. var checkAll = that.data.length === that.$selectItem.filter(':checked').length;
  338. that.$selectAll.prop('checked', checkAll);
  339. that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked');
  340. });
  341. this.resetView();
  342. };
  343. BootstrapTable.prototype.initServer = function() {
  344. var that = this;
  345. if (!this.options.url) {
  346. return;
  347. }
  348. $.ajax({
  349. type: this.options.method,
  350. url: this.options.url,
  351. data: this.options.queryParams,
  352. contentType: 'application/json',
  353. dataType: 'json',
  354. success: function(data) {
  355. that.load(data);
  356. }
  357. });
  358. };
  359. BootstrapTable.prototype.getCaretHtml = function() {
  360. return ['<span class="order' + (this.options.sortOrder === 'desc' ? '' : ' dropup') + '">',
  361. '<span class="caret" style="margin: 10px 5px;"></span>',
  362. '</span>'].join('');
  363. };
  364. BootstrapTable.prototype.resetView = function() {
  365. var header = this.header;
  366. this.$header.find('.th-inner').each(function(i) {
  367. $(this).attr('style', header.styles[i])
  368. .css('width', ($(this).parent().width()) + 'px'); // padding: 8px
  369. });
  370. };
  371. BootstrapTable.prototype.updateRows = function(checked) {
  372. var that = this;
  373. $.each(this.data, function(i, row) {
  374. row[that.header.stateField] = checked;
  375. });
  376. };
  377. // PUBLIC FUNCTION DEFINITION
  378. // =======================
  379. BootstrapTable.prototype.load = function(data) {
  380. this.initData(data);
  381. this.initPagination();
  382. this.initBody();
  383. };
  384. BootstrapTable.prototype.append = function(data) {
  385. this.initData(data, true);
  386. this.initBody();
  387. };
  388. BootstrapTable.prototype.mergeCells = function(options) {
  389. var row = options.index,
  390. col = $.inArray(options.field, this.header.fields),
  391. rowspan = options.rowspan || 1,
  392. colspan = options.colspan || 1,
  393. i, j,
  394. $tr = this.$body.find('tr'),
  395. $td = $tr.eq(row).find('td').eq(col);
  396. if (row < 0 || col < 0 || row >= this.data.length) {
  397. return;
  398. }
  399. for (i = row; i < row + rowspan; i++) {
  400. for (j = col; j < col + colspan; j++) {
  401. $tr.eq(i).find('td').eq(j).hide();
  402. }
  403. }
  404. $td.attr('rowspan', rowspan).attr('colspan', colspan).show();
  405. };
  406. BootstrapTable.prototype.getSelections = function() {
  407. var that = this;
  408. return $.grep(this.data, function(row) {
  409. return row[that.header.stateField];
  410. });
  411. };
  412. BootstrapTable.prototype.checkAll = function() {
  413. this.$selectAll.prop('checked', true);
  414. this.$selectItem.prop('checked', true);
  415. this.updateRows(true);
  416. };
  417. BootstrapTable.prototype.uncheckAll = function() {
  418. this.$selectAll.prop('checked', false);
  419. this.$selectItem.prop('checked', false);
  420. this.updateRows(false);
  421. };
  422. // BOOTSTRAP TABLE PLUGIN DEFINITION
  423. // =======================
  424. $.fn.bootstrapTable = function(option, _relatedTarget) {
  425. var allowedMethods = [
  426. 'getSelections',
  427. 'load', 'append', 'mergeCells',
  428. 'checkAll', 'uncheckAll'
  429. ],
  430. value;
  431. this.each(function() {
  432. var $this = $(this),
  433. data = $this.data('bootstrap.table'),
  434. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(), typeof option === 'object' && option);
  435. if (!data) {
  436. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  437. }
  438. if (typeof option === 'string') {
  439. if ($.inArray(option, allowedMethods) < 0) {
  440. throw "Unknown method: " + option;
  441. }
  442. value = data[option](_relatedTarget);
  443. }
  444. });
  445. return value ? value : this;
  446. };
  447. $.fn.bootstrapTable.Constructor = BootstrapTable;
  448. // BOOTSTRAP TABLE INIT
  449. // =======================
  450. $(function() {
  451. $('[data-toggle="table"]').bootstrapTable();
  452. });
  453. }(jQuery);