bootstrap-table.js 40 KB

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