bootstrap-table.js 47 KB

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