bootstrap-table.js 36 KB

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