bootstrap-table.js 42 KB

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