bootstrap-table.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  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 calculateFunctionValue = function (self, 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(self, 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. });
  326. this.$container.off('click', 'th').on('click', 'th', function (event) {
  327. if (that.options.sortable && $(this).data().sortable) {
  328. that.onSort(event);
  329. }
  330. });
  331. if (!this.options.showHeader || this.options.cardView) {
  332. this.$header.hide();
  333. this.$container.find('.fixed-table-header').hide();
  334. this.$loading.css('top', 0);
  335. } else {
  336. this.$header.show();
  337. this.$container.find('.fixed-table-header').show();
  338. this.$loading.css('top', '37px');
  339. }
  340. this.$selectAll = this.$header.find('[name="btSelectAll"]');
  341. this.$selectAll.off('click').on('click', function () {
  342. var checked = $(this).prop('checked');
  343. that[checked ? 'checkAll' : 'uncheckAll']();
  344. });
  345. };
  346. BootstrapTable.prototype.initData = function (data, append) {
  347. if (append) {
  348. this.data = this.data.concat(data);
  349. } else {
  350. this.data = data || this.options.data;
  351. }
  352. this.options.data = this.data;
  353. this.initSort();
  354. };
  355. BootstrapTable.prototype.initSort = function () {
  356. var that = this,
  357. name = this.options.sortName,
  358. order = this.options.sortOrder === 'desc' ? -1 : 1,
  359. index = $.inArray(this.options.sortName, this.header.fields);
  360. if (index !== -1) {
  361. this.data.sort(function (a, b) {
  362. var value = calculateFunctionValue(that.header, that.header.sorters[index], [a[name], b[name]]);
  363. if (value !== undefined) {
  364. return order * value;
  365. }
  366. if (a[name] === b[name]) {
  367. return 0;
  368. }
  369. if (a[name] < b[name]) {
  370. return order * -1;
  371. }
  372. return order;
  373. });
  374. }
  375. };
  376. BootstrapTable.prototype.onSort = function (event) {
  377. var $this = $(event.currentTarget),
  378. $this_ = this.$header.find('th').eq($this.index());
  379. this.$header.add(this.$header_).find('span.order').remove();
  380. if (this.options.sortName === $this.data('field')) {
  381. this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc';
  382. } else {
  383. this.options.sortName = $this.data('field');
  384. this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
  385. }
  386. this.trigger('sort', this.options.sortName, this.options.sortOrder);
  387. $this.add($this_).data('order', this.options.sortOrder)
  388. .find('.th-inner').append(this.getCaretHtml());
  389. if (this.options.sidePagination === 'server') {
  390. this.initServer();
  391. return;
  392. }
  393. this.initSort();
  394. this.initBody();
  395. };
  396. BootstrapTable.prototype.initToolbar = function () {
  397. var that = this,
  398. html = [],
  399. timeoutId = 0,
  400. $keepOpen,
  401. $search;
  402. this.$toolbar = this.$container.find('.fixed-table-toolbar').html('');
  403. if (typeof this.options.toolbar === 'string') {
  404. $('<div class="bars pull-left"></div>')
  405. .appendTo(this.$toolbar)
  406. .append($(this.options.toolbar));
  407. }
  408. // showColumns, showToggle, showRefresh
  409. html = ['<div class="columns btn-group pull-right">'];
  410. if (this.options.showRefresh) {
  411. html.push('<button class="btn btn-default" type="button" name="refresh">',
  412. '<i class="glyphicon glyphicon-refresh icon-refresh"></i>',
  413. '</button>');
  414. }
  415. if (this.options.showToggle) {
  416. html.push('<button class="btn btn-default" type="button" name="toggle">',
  417. '<i class="glyphicon glyphicon glyphicon-list-alt icon-list-alt"></i>',
  418. '</button>');
  419. }
  420. if (this.options.showColumns) {
  421. html.push(sprintf('<div class="keep-open %s">',
  422. this.options.showRefresh || this.options.showToggle ? 'btn-group' : ''),
  423. '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">',
  424. '<i class="glyphicon glyphicon-th icon-th"></i>',
  425. ' <span class="caret"></span>',
  426. '</button>',
  427. '<ul class="dropdown-menu" role="menu">');
  428. $.each(this.options.columns, function (i, column) {
  429. if (column.radio || column.checkbox) {
  430. return;
  431. }
  432. var checked = column.visible ? ' checked="checked"' : '';
  433. if (column.switchable) {
  434. html.push(sprintf('<li>' +
  435. '<label><input type="checkbox" value="%s"%s> %s</label>' +
  436. '</li>', i, checked, column.title));
  437. }
  438. });
  439. html.push('</ul>',
  440. '</div>');
  441. }
  442. html.push('</div>');
  443. if (html.length > 2) {
  444. this.$toolbar.append(html.join(''));
  445. }
  446. if (this.options.showRefresh) {
  447. this.$toolbar.find('button[name="refresh"]')
  448. .off('click').on('click', $.proxy(this.refresh, this));
  449. }
  450. if (this.options.showToggle) {
  451. this.$toolbar.find('button[name="toggle"]')
  452. .off('click').on('click', function () {
  453. that.options.cardView = !that.options.cardView;
  454. that.initHeader();
  455. that.initBody();
  456. });
  457. }
  458. if (this.options.showColumns) {
  459. $keepOpen = this.$toolbar.find('.keep-open');
  460. $keepOpen.find('li').off('click').on('click', function (event) {
  461. event.stopImmediatePropagation();
  462. });
  463. $keepOpen.find('input').off('click').on('click', function () {
  464. var $this = $(this);
  465. that.toggleColumn($this.val(), $this.prop('checked'), false);
  466. });
  467. }
  468. if (this.options.search) {
  469. html = [];
  470. html.push(
  471. '<div class="pull-right search">',
  472. sprintf('<input class="form-control" type="text" placeholder="%s">',
  473. this.options.formatSearch()),
  474. '</div>');
  475. this.$toolbar.append(html.join(''));
  476. $search = this.$toolbar.find('.search input');
  477. $search.off('keyup').on('keyup', function (event) {
  478. clearTimeout(timeoutId); // doesn't matter if it's 0
  479. timeoutId = setTimeout(function () {
  480. that.onSearch(event);
  481. }, 500); // 500ms
  482. });
  483. }
  484. };
  485. BootstrapTable.prototype.onSearch = function (event) {
  486. var text = $.trim($(event.currentTarget).val());
  487. if (text === this.searchText) {
  488. return;
  489. }
  490. this.searchText = text;
  491. this.options.pageNumber = 1;
  492. this.initSearch();
  493. this.updatePagination();
  494. };
  495. BootstrapTable.prototype.initSearch = function () {
  496. var that = this;
  497. if (this.options.sidePagination !== 'server') {
  498. var s = this.searchText && this.searchText.toLowerCase();
  499. this.data = s ? $.grep(this.options.data, function (item) {
  500. key = $.isNumeric(key) ? parseInt(key): key ;
  501. for (var key in item) {
  502. if ($.inArray(key, that.header.fields) !== -1 &&
  503. (typeof item[key] === 'string' ||
  504. typeof item[key] === 'number') &&
  505. (item[key] + '').toLowerCase().indexOf(s) !== -1) {
  506. return true;
  507. }
  508. }
  509. return false;
  510. }) : this.options.data;
  511. }
  512. };
  513. BootstrapTable.prototype.initPagination = function () {
  514. this.$pagination = this.$container.find('.fixed-table-pagination');
  515. if (!this.options.pagination) {
  516. return;
  517. }
  518. var that = this,
  519. html = [],
  520. i, from, to,
  521. $pageList,
  522. $first, $pre,
  523. $next, $last,
  524. $number,
  525. data = this.searchText ? this.data : this.options.data;
  526. if (this.options.sidePagination !== 'server') {
  527. this.options.totalRows = data.length;
  528. }
  529. this.totalPages = 0;
  530. if (this.options.totalRows) {
  531. this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
  532. }
  533. if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
  534. this.options.pageNumber = this.totalPages;
  535. }
  536. this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
  537. this.pageTo = this.options.pageNumber * this.options.pageSize;
  538. if (this.pageTo > this.options.totalRows) {
  539. this.pageTo = this.options.totalRows;
  540. }
  541. html.push(
  542. '<div class="pull-left pagination-detail">',
  543. '<span class="pagination-info">',
  544. this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
  545. '</span>');
  546. html.push('<span class="page-list">');
  547. var pageNumber = [
  548. '<span class="btn-group dropup">',
  549. '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">',
  550. '<span class="page-size">',
  551. this.options.pageSize,
  552. '</span>',
  553. ' <span class="caret"></span>',
  554. '</button>',
  555. '<ul class="dropdown-menu" role="menu">'],
  556. pageList = this.options.pageList;
  557. if (typeof this.options.pageList === 'string') {
  558. var list = this.options.pageList.slice(1, -1).replace(/ /g, '').split(',');
  559. pageList = [];
  560. $.each(list, function (i, value) {
  561. pageList.push(+value);
  562. });
  563. }
  564. $.each(pageList, function (i, page) {
  565. var active = page === that.options.pageSize ? ' class="active"' : '';
  566. pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page));
  567. });
  568. pageNumber.push('</ul></span>');
  569. html.push(this.options.formatRecordsPerPage(pageNumber.join('')));
  570. html.push('</span>');
  571. html.push('</div>',
  572. '<div class="pull-right pagination">',
  573. '<ul class="pagination">',
  574. '<li class="page-first"><a href="javascript:void(0)">&lt;&lt;</a></li>',
  575. '<li class="page-pre"><a href="javascript:void(0)">&lt;</a></li>');
  576. if (this.totalPages < 5) {
  577. from = 1;
  578. to = this.totalPages;
  579. } else {
  580. from = this.options.pageNumber - 2;
  581. to = from + 4;
  582. if (from < 1) {
  583. from = 1;
  584. to = 5;
  585. }
  586. if (to > this.totalPages) {
  587. to = this.totalPages;
  588. from = to - 4;
  589. }
  590. }
  591. for (i = from; i <= to; i++) {
  592. html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
  593. '<a href="javascript:void(0)">', i ,'</a>',
  594. '</li>');
  595. }
  596. html.push(
  597. '<li class="page-next"><a href="javascript:void(0)">&gt;</a></li>',
  598. '<li class="page-last"><a href="javascript:void(0)">&gt;&gt;</a></li>',
  599. '</ul>',
  600. '</div>');
  601. this.$pagination.html(html.join(''));
  602. $pageList = this.$pagination.find('.page-list a');
  603. $first = this.$pagination.find('.page-first');
  604. $pre = this.$pagination.find('.page-pre');
  605. $next = this.$pagination.find('.page-next');
  606. $last = this.$pagination.find('.page-last');
  607. $number = this.$pagination.find('.page-number');
  608. if (this.options.pageNumber <= 1) {
  609. $first.addClass('disabled');
  610. $pre.addClass('disabled');
  611. }
  612. if (this.options.pageNumber >= this.totalPages) {
  613. $next.addClass('disabled');
  614. $last.addClass('disabled');
  615. }
  616. $pageList.off('click').on('click', $.proxy(this.onPageListChange, this));
  617. $first.off('click').on('click', $.proxy(this.onPageFirst, this));
  618. $pre.off('click').on('click', $.proxy(this.onPagePre, this));
  619. $next.off('click').on('click', $.proxy(this.onPageNext, this));
  620. $last.off('click').on('click', $.proxy(this.onPageLast, this));
  621. $number.off('click').on('click', $.proxy(this.onPageNumber, this));
  622. };
  623. BootstrapTable.prototype.updatePagination = function () {
  624. if (!this.options.maintainSelected) {
  625. this.resetRows();
  626. }
  627. this.initPagination();
  628. if (this.options.sidePagination === 'server') {
  629. this.initServer();
  630. } else {
  631. this.initBody();
  632. }
  633. };
  634. BootstrapTable.prototype.onPageListChange = function (event) {
  635. var $this = $(event.currentTarget);
  636. $this.parent().addClass('active').siblings().removeClass('active');
  637. this.options.pageSize = +$this.text();
  638. this.$toolbar.find('.page-size').text(this.options.pageSize);
  639. this.updatePagination();
  640. };
  641. BootstrapTable.prototype.onPageFirst = function () {
  642. this.options.pageNumber = 1;
  643. this.updatePagination();
  644. };
  645. BootstrapTable.prototype.onPagePre = function () {
  646. this.options.pageNumber--;
  647. this.updatePagination();
  648. };
  649. BootstrapTable.prototype.onPageNext = function () {
  650. this.options.pageNumber++;
  651. this.updatePagination();
  652. };
  653. BootstrapTable.prototype.onPageLast = function () {
  654. this.options.pageNumber = this.totalPages;
  655. this.updatePagination();
  656. };
  657. BootstrapTable.prototype.onPageNumber = function (event) {
  658. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  659. return;
  660. }
  661. this.options.pageNumber = +$(event.currentTarget).text();
  662. this.updatePagination();
  663. };
  664. BootstrapTable.prototype.initBody = function (fixedScroll) {
  665. var that = this,
  666. html = [],
  667. data = this.getData();
  668. this.$body = this.$el.find('tbody');
  669. if (!this.$body.length) {
  670. this.$body = $('<tbody></tbody>').appendTo(this.$el);
  671. }
  672. if (this.options.sidePagination === 'server') {
  673. data = this.data;
  674. }
  675. if (!this.options.pagination || this.options.sidePagination === 'server') {
  676. this.pageFrom = 1;
  677. this.pageTo = data.length;
  678. }
  679. for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
  680. var item = data[i],
  681. style = {},
  682. csses = [];
  683. style = calculateFunctionValue(this.options, this.options.rowStyle, [item, i], style);
  684. if (style && style.css) {
  685. for (var key in style.css) {
  686. csses.push(key + ': ' + style.css[key]);
  687. }
  688. }
  689. html.push('<tr',
  690. sprintf(' class="%s"', style.classes),
  691. sprintf(' data-index="%s"', i),
  692. '>'
  693. );
  694. if (this.options.cardView) {
  695. html.push(sprintf('<td colspan="%s">', this.header.fields.length));
  696. }
  697. $.each(this.header.fields, function (j, field) {
  698. var text = '',
  699. value = item[field],
  700. type = '',
  701. cellStyle = {},
  702. class_ = that.header.classes[j];
  703. style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
  704. value = calculateFunctionValue(that.header,
  705. that.header.formatters[j], [value, item, i], value);
  706. cellStyle = calculateFunctionValue(that.header,
  707. that.header.cellStyles[j], [value, item, i], cellStyle);
  708. if (cellStyle.classes) {
  709. class_ = sprintf(' class="%s"', cellStyle.classes);
  710. }
  711. if (cellStyle.css) {
  712. csses = [];
  713. for (var key in cellStyle.css) {
  714. csses.push(key + ': ' + cellStyle.css[key]);
  715. }
  716. style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
  717. }
  718. if (that.options.columns[j].checkbox || that.options.columns[j].radio) {
  719. //if card view mode bypass
  720. if (that.options.cardView) {
  721. return true;
  722. }
  723. type = that.options.columns[j].checkbox ? 'checkbox' : type;
  724. type = that.options.columns[j].radio ? 'radio' : type;
  725. text = ['<td class="bs-checkbox">',
  726. '<input' +
  727. sprintf(' data-index="%s"', i) +
  728. sprintf(' name="%s"', that.options.selectItemName) +
  729. sprintf(' type="%s"', type) +
  730. sprintf(' value="%s"', item[that.options.idField]) +
  731. sprintf(' checked="%s"', value ? 'checked' : undefined) +
  732. sprintf(' %s', that.options.columns[j].checkboxEnabled ? undefined : 'disabled') +
  733. ' />',
  734. '</td>'].join('');
  735. } else {
  736. value = typeof value === 'undefined' ? that.options.undefinedText : value;
  737. text = that.options.cardView ?
  738. ['<div class="card-view">',
  739. that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style,
  740. getPropertyFromOther(that.options.columns, 'field', 'title', field)) : '',
  741. sprintf('<span class="value">%s</span>', value),
  742. '</div>'].join('') :
  743. [sprintf('<td%s %s>', class_, style),
  744. value,
  745. '</td>'].join('');
  746. }
  747. html.push(text);
  748. });
  749. if (this.options.cardView) {
  750. html.push('</td>');
  751. }
  752. html.push('</tr>');
  753. }
  754. // show no records
  755. if (!html.length) {
  756. html.push('<tr class="no-records-found">',
  757. sprintf('<td colspan="%s">%s</td>', this.header.fields.length, this.options.formatNoMatches()),
  758. '</tr>');
  759. }
  760. this.$body.html(html.join(''));
  761. if (!fixedScroll) {
  762. this.$container.find('.fixed-table-body').scrollTop(0);
  763. }
  764. // click to select by column
  765. this.$body.find('> tr > td').off('click').on('click', function () {
  766. var $tr = $(this).parent();
  767. that.trigger('click-row', that.data[$tr.data('index')], $tr);
  768. // if click to select - then trigger the checkbox/radio click
  769. if (that.options.clickToSelect) {
  770. if (that.header.clickToSelects[$tr.children().index($(this))]) {
  771. $tr.find(sprintf('[name="%s"]',
  772. that.options.selectItemName)).trigger('click');
  773. }
  774. }
  775. });
  776. this.$body.find('tr').off('dblclick').on('dblclick', function () {
  777. that.trigger('dbl-click-row', that.data[$(this).data('index')], $(this));
  778. });
  779. this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
  780. this.$selectItem.off('click').on('click', function (event) {
  781. event.stopImmediatePropagation();
  782. // radio trigger click event bug!
  783. if ($(this).is(':radio')) {
  784. $(this).prop('checked', true);
  785. }
  786. var checkAll = that.$selectItem.length === that.$selectItem.filter(':checked').length,
  787. checked = $(this).prop('checked'),
  788. row = that.data[$(this).data('index')];
  789. that.$selectAll.add(that.$selectAll_).prop('checked', checkAll);
  790. row[that.header.stateField] = checked;
  791. that.trigger(checked ? 'check' : 'uncheck', row);
  792. if (that.options.singleSelect) {
  793. that.$selectItem.not(this).each(function () {
  794. that.data[$(this).data('index')][that.header.stateField] = false;
  795. });
  796. that.$selectItem.filter(':checked').not(this).prop('checked', false);
  797. }
  798. that.updateSelected();
  799. });
  800. $.each(this.header.events, function (i, events) {
  801. if (!events) {
  802. return;
  803. }
  804. if (typeof events === 'string') {
  805. events = window[events];
  806. }
  807. for (var key in events) {
  808. that.$body.find('tr').each(function () {
  809. var $tr = $(this),
  810. $td = $tr.find('td').eq(i),
  811. index = key.indexOf(' '),
  812. name = key.substring(0, index),
  813. el = key.substring(index + 1),
  814. func = events[key];
  815. $td.find(el).off(name).on(name, function (e) {
  816. var index = $tr.data('index'),
  817. row = that.data[index],
  818. value = row[that.header.fields[i]];
  819. func(e, value, row, index);
  820. });
  821. });
  822. }
  823. });
  824. this.updateSelected();
  825. this.resetView();
  826. };
  827. BootstrapTable.prototype.initServer = function (silent) {
  828. var that = this,
  829. data = {},
  830. params = {
  831. pageSize: this.options.pageSize,
  832. pageNumber: this.options.pageNumber,
  833. searchText: this.searchText,
  834. sortName: this.options.sortName,
  835. sortOrder: this.options.sortOrder
  836. };
  837. if (!this.options.url) {
  838. return;
  839. }
  840. if (!silent) {
  841. this.$loading.show();
  842. }
  843. if (this.options.queryParamsType === 'limit') {
  844. params = {
  845. limit: params.pageSize,
  846. offset: params.pageSize * (params.pageNumber - 1),
  847. search: params.searchText,
  848. sort: params.sortName,
  849. order: params.sortOrder
  850. };
  851. }
  852. data = calculateFunctionValue(this.options, this.options.queryParams, [params], data);
  853. $.ajax({
  854. type: this.options.method,
  855. url: this.options.url,
  856. data: data,
  857. cache: this.options.cache,
  858. contentType: this.options.contentType,
  859. dataType: 'json',
  860. success: function (res) {
  861. res = calculateFunctionValue(that.options, that.options.responseHandler, [res], res);
  862. var data = res;
  863. if (that.options.sidePagination === 'server') {
  864. that.options.totalRows = res.total;
  865. data = res.rows;
  866. }
  867. that.load(data);
  868. that.trigger('load-success', data);
  869. },
  870. error: function (res) {
  871. that.trigger('load-error', res.status);
  872. },
  873. complete: function () {
  874. if (!silent) {
  875. that.$loading.hide();
  876. }
  877. }
  878. });
  879. };
  880. BootstrapTable.prototype.getCaretHtml = function () {
  881. return ['<span class="order' + (this.options.sortOrder === 'desc' ? '' : ' dropup') + '">',
  882. '<span class="caret" style="margin: 10px 5px;"></span>',
  883. '</span>'].join('');
  884. };
  885. BootstrapTable.prototype.updateSelected = function () {
  886. this.$selectItem.each(function () {
  887. $(this).parents('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
  888. });
  889. };
  890. BootstrapTable.prototype.updateRows = function (checked) {
  891. var that = this;
  892. this.$selectItem.each(function () {
  893. that.data[$(this).data('index')][that.header.stateField] = checked;
  894. });
  895. };
  896. BootstrapTable.prototype.resetRows = function () {
  897. var that = this;
  898. $.each(this.data, function (i, row) {
  899. that.$selectAll.prop('checked', false);
  900. that.$selectItem.prop('checked', false);
  901. row[that.header.stateField] = false;
  902. });
  903. };
  904. BootstrapTable.prototype.trigger = function (name) {
  905. var args = Array.prototype.slice.call(arguments, 1);
  906. name += '.bs.table';
  907. this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
  908. this.$el.trigger($.Event(name), args);
  909. this.options.onAll(name, args);
  910. this.$el.trigger($.Event('all.bs.table'), [name, args]);
  911. };
  912. BootstrapTable.prototype.resetHeader = function () {
  913. var that = this,
  914. $fixedHeader = this.$container.find('.fixed-table-header'),
  915. $fixedBody = this.$container.find('.fixed-table-body'),
  916. scrollWidth = this.$el.width() > $fixedBody.width() ? getScrollBarWidth() : 0;
  917. // fix #61: the hidden table reset header bug.
  918. if (this.$el.is(':hidden')) {
  919. clearTimeout(this.timeoutId_); // doesn't matter if it's 0
  920. this.timeoutId_ = setTimeout($.proxy(this.resetHeader, this), 100); // 100ms
  921. return;
  922. }
  923. this.$header_ = this.$header.clone(true, true);
  924. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
  925. // fix bug: get $el.css('width') error sometime (height = 500)
  926. setTimeout(function () {
  927. $fixedHeader.css({
  928. 'height': '37px',
  929. 'border-bottom': '1px solid #dddddd',
  930. 'margin-right': scrollWidth
  931. }).find('table').css('width', that.$el.css('width'))
  932. .html('').attr('class', that.$el.attr('class'))
  933. .append(that.$header_);
  934. // fix bug: $.data() is not working as expected after $.append()
  935. that.$header.find('th').each(function (i) {
  936. that.$header_.find('th').eq(i).data($(this).data());
  937. });
  938. that.$body.find('tr:first-child:not(.no-records-found) > *').each(function(i) {
  939. that.$header_.find('div.fht-cell').eq(i).width($(this).innerWidth());
  940. });
  941. that.$el.css('margin-top', -that.$header.height());
  942. // horizontal scroll event
  943. $fixedBody.off('scroll').on('scroll', function () {
  944. $fixedHeader.scrollLeft($(this).scrollLeft());
  945. });
  946. });
  947. };
  948. BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
  949. if (index === -1) {
  950. return;
  951. }
  952. this.options.columns[index].visible = checked;
  953. this.initHeader();
  954. this.initSearch();
  955. this.initPagination();
  956. this.initBody();
  957. if (this.options.showColumns) {
  958. var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
  959. if (needUpdate) {
  960. $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
  961. }
  962. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  963. $items.filter(':checked').prop('disabled', true);
  964. }
  965. }
  966. };
  967. // PUBLIC FUNCTION DEFINITION
  968. // =======================
  969. BootstrapTable.prototype.resetView = function (params) {
  970. var that = this,
  971. header = this.header;
  972. if (params && params.height) {
  973. this.options.height = params.height;
  974. }
  975. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  976. this.$selectItem.length === this.$selectItem.filter(':checked').length);
  977. if (this.options.height) {
  978. var toolbarHeight = +this.$toolbar.children().outerHeight(true),
  979. paginationHeight = +this.$pagination.children().outerHeight(true),
  980. height = this.options.height - toolbarHeight - paginationHeight;
  981. this.$container.find('.fixed-table-container').css('height', height + 'px');
  982. }
  983. if (this.options.cardView) {
  984. // remove the element css
  985. that.$el.css('margin-top', '0');
  986. that.$container.find('.fixed-table-container').css('padding-bottom', '0');
  987. return;
  988. }
  989. if (this.options.showHeader && this.options.height) {
  990. this.resetHeader();
  991. }
  992. if (this.options.height && this.options.showHeader) {
  993. this.$container.find('.fixed-table-container').css('padding-bottom', '37px');
  994. }
  995. };
  996. BootstrapTable.prototype.getData = function () {
  997. return this.searchText ? this.data : this.options.data;
  998. };
  999. BootstrapTable.prototype.load = function (data) {
  1000. this.initData(data);
  1001. this.initSearch();
  1002. this.initPagination();
  1003. this.initBody();
  1004. };
  1005. BootstrapTable.prototype.append = function (data) {
  1006. this.initData(data, true);
  1007. this.initSearch();
  1008. this.initPagination();
  1009. this.initBody(true);
  1010. };
  1011. BootstrapTable.prototype.remove = function (params) {
  1012. var len = this.options.data.length,
  1013. i, row;
  1014. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  1015. return;
  1016. }
  1017. for (i = len - 1; i >= 0; i--) {
  1018. row = this.options.data[i];
  1019. if (!row.hasOwnProperty(params.field)) {
  1020. return;
  1021. }
  1022. if ($.inArray(row[params.field], params.values) !== -1) {
  1023. this.options.data.splice(i, 1);
  1024. }
  1025. }
  1026. if (len === this.options.data.length) {
  1027. return;
  1028. }
  1029. this.initSearch();
  1030. this.initPagination();
  1031. this.initBody(true);
  1032. };
  1033. BootstrapTable.prototype.updateRow = function (params) {
  1034. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1035. return;
  1036. }
  1037. $.extend(this.data[params.index], params.row);
  1038. this.initBody();
  1039. };
  1040. BootstrapTable.prototype.mergeCells = function (options) {
  1041. var row = options.index,
  1042. col = $.inArray(options.field, this.header.fields),
  1043. rowspan = options.rowspan || 1,
  1044. colspan = options.colspan || 1,
  1045. i, j,
  1046. $tr = this.$body.find('tr'),
  1047. $td = $tr.eq(row).find('td').eq(col);
  1048. if (row < 0 || col < 0 || row >= this.data.length) {
  1049. return;
  1050. }
  1051. for (i = row; i < row + rowspan; i++) {
  1052. for (j = col; j < col + colspan; j++) {
  1053. $tr.eq(i).find('td').eq(j).hide();
  1054. }
  1055. }
  1056. $td.attr('rowspan', rowspan).attr('colspan', colspan)
  1057. .show(10, $.proxy(this.resetView, this));
  1058. };
  1059. BootstrapTable.prototype.getSelections = function () {
  1060. var that = this;
  1061. return $.grep(this.data, function (row) {
  1062. return row[that.header.stateField];
  1063. });
  1064. };
  1065. BootstrapTable.prototype.checkAll = function () {
  1066. this.$selectAll.add(this.$selectAll_).prop('checked', true);
  1067. this.$selectItem.prop('checked', true);
  1068. this.updateRows(true);
  1069. this.updateSelected();
  1070. this.trigger('check-all');
  1071. };
  1072. BootstrapTable.prototype.uncheckAll = function () {
  1073. this.$selectAll.add(this.$selectAll_).prop('checked', false);
  1074. this.$selectItem.prop('checked', false);
  1075. this.updateRows(false);
  1076. this.updateSelected();
  1077. this.trigger('uncheck-all');
  1078. };
  1079. BootstrapTable.prototype.destroy = function () {
  1080. this.$el.insertBefore(this.$container);
  1081. $(this.options.toolbar).insertBefore(this.$el);
  1082. this.$container.next().remove();
  1083. this.$container.remove();
  1084. this.$el.html(this.$el_.html())
  1085. .attr('class', this.$el_.attr('class') || ''); // reset the class
  1086. };
  1087. BootstrapTable.prototype.showLoading = function () {
  1088. this.$loading.show();
  1089. };
  1090. BootstrapTable.prototype.hideLoading = function () {
  1091. this.$loading.hide();
  1092. };
  1093. BootstrapTable.prototype.refresh = function (params) {
  1094. if (params && params.url) {
  1095. this.options.url = params.url;
  1096. }
  1097. this.initServer(params && params.silent);
  1098. };
  1099. BootstrapTable.prototype.showColumn = function (field) {
  1100. this.toggleColumn(getFieldIndex(this.options.columns, field), true, true);
  1101. };
  1102. BootstrapTable.prototype.hideColumn = function (field) {
  1103. this.toggleColumn(getFieldIndex(this.options.columns, field), false, true);
  1104. };
  1105. // BOOTSTRAP TABLE PLUGIN DEFINITION
  1106. // =======================
  1107. $.fn.bootstrapTable = function (option, _relatedTarget) {
  1108. var allowedMethods = [
  1109. 'getSelections', 'getData',
  1110. 'load', 'append', 'remove',
  1111. 'updateRow',
  1112. 'mergeCells',
  1113. 'checkAll', 'uncheckAll',
  1114. 'refresh',
  1115. 'resetView',
  1116. 'destroy',
  1117. 'showLoading', 'hideLoading',
  1118. 'showColumn', 'hideColumn'
  1119. ],
  1120. value;
  1121. this.each(function () {
  1122. var $this = $(this),
  1123. data = $this.data('bootstrap.table'),
  1124. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
  1125. typeof option === 'object' && option);
  1126. if (typeof option === 'string') {
  1127. if ($.inArray(option, allowedMethods) < 0) {
  1128. throw "Unknown method: " + option;
  1129. }
  1130. if (!data) {
  1131. return;
  1132. }
  1133. value = data[option](_relatedTarget);
  1134. if (option === 'destroy') {
  1135. $this.removeData('bootstrap.table');
  1136. }
  1137. }
  1138. if (!data) {
  1139. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  1140. }
  1141. });
  1142. return typeof value === 'undefined' ? this : value;
  1143. };
  1144. $.fn.bootstrapTable.Constructor = BootstrapTable;
  1145. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
  1146. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
  1147. // BOOTSTRAP TABLE INIT
  1148. // =======================
  1149. $(function () {
  1150. $('[data-toggle="table"]').bootstrapTable();
  1151. });
  1152. }(jQuery);