bootstrap-table.js 45 KB

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