bootstrap-table.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  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 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. cellStyle = {},
  696. class_ = that.header.classes[j];
  697. style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
  698. value = calculateFunctionValue(that.header.formatters[j], [value, item, i], value);
  699. cellStyle = calculateFunctionValue(that.header.cellStyles[j], [value, item, i], cellStyle);
  700. if (cellStyle.classes) {
  701. class_ = sprintf(' class="%s"', cellStyle.classes);
  702. }
  703. if (cellStyle.css) {
  704. csses = [];
  705. for (var key in cellStyle.css) {
  706. csses.push(key + ': ' + cellStyle.css[key]);
  707. }
  708. style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
  709. }
  710. if (that.options.columns[j].checkbox || that.options.columns[j].radio) {
  711. //if card view mode bypass
  712. if (that.options.cardView) {
  713. return true;
  714. }
  715. type = that.options.columns[j].checkbox ? 'checkbox' : type;
  716. type = that.options.columns[j].radio ? 'radio' : type;
  717. text = ['<td class="bs-checkbox">',
  718. '<input' +
  719. sprintf(' data-index="%s"', i) +
  720. sprintf(' name="%s"', that.options.selectItemName) +
  721. sprintf(' type="%s"', type) +
  722. sprintf(' value="%s"', item[that.options.idField]) +
  723. sprintf(' checked="%s"', value ? 'checked' : undefined) +
  724. sprintf(' %s', that.options.columns[j].checkboxEnabled ? undefined : 'disabled') +
  725. ' />',
  726. '</td>'].join('');
  727. } else {
  728. value = typeof value === 'undefined' ? that.options.undefinedText : value;
  729. text = that.options.cardView ?
  730. ['<div class="card-view">',
  731. sprintf('<span class="title" %s>%s</span>', style,
  732. getPropertyFromOther(that.options.columns, 'field', 'title', field)),
  733. sprintf('<span class="value">%s</span>', value),
  734. '</div>'].join('') :
  735. [sprintf('<td%s %s>', class_, style),
  736. value,
  737. '</td>'].join('');
  738. }
  739. html.push(text);
  740. });
  741. if (this.options.cardView) {
  742. html.push('</td>');
  743. }
  744. html.push('</tr>');
  745. }
  746. // show no records
  747. if (!html.length) {
  748. html.push('<tr class="no-records-found">',
  749. sprintf('<td colspan="%s">%s</td>', this.header.fields.length, this.options.formatNoMatches()),
  750. '</tr>');
  751. }
  752. this.$body.html(html.join(''));
  753. if (!fixedScroll) {
  754. this.$container.find('.fixed-table-body').scrollTop(0);
  755. }
  756. // click to select by column
  757. this.$body.find('> tr > td').off('click').on('click', function () {
  758. var $tr = $(this).parent();
  759. that.trigger('click-row', that.data[$tr.data('index')], $tr);
  760. // if click to select - then trigger the checkbox/radio click
  761. if (that.options.clickToSelect) {
  762. if (that.header.clickToSelects[$tr.children().index($(this))]) {
  763. $tr.find(sprintf('[name="%s"]',
  764. that.options.selectItemName)).trigger('click');
  765. }
  766. }
  767. });
  768. this.$body.find('tr').off('dblclick').on('dblclick', function () {
  769. that.trigger('dbl-click-row', that.data[$(this).data('index')], $(this));
  770. });
  771. this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
  772. this.$selectItem.off('click').on('click', function (event) {
  773. event.stopImmediatePropagation();
  774. // radio trigger click event bug!
  775. if ($(this).is(':radio')) {
  776. $(this).prop('checked', true);
  777. }
  778. var checkAll = that.$selectItem.length === that.$selectItem.filter(':checked').length,
  779. checked = $(this).prop('checked'),
  780. row = that.data[$(this).data('index')];
  781. that.$selectAll.add(that.$selectAll_).prop('checked', checkAll);
  782. row[that.header.stateField] = checked;
  783. that.trigger(checked ? 'check' : 'uncheck', row);
  784. if (that.options.singleSelect) {
  785. that.$selectItem.not(this).each(function () {
  786. that.data[$(this).data('index')][that.header.stateField] = false;
  787. });
  788. that.$selectItem.filter(':checked').not(this).prop('checked', false);
  789. }
  790. that.updateSelected();
  791. });
  792. $.each(this.header.events, function (i, events) {
  793. if (!events) {
  794. return;
  795. }
  796. if (typeof events === 'string') {
  797. events = window[events];
  798. }
  799. for (var key in events) {
  800. that.$body.find('tr').each(function () {
  801. var $tr = $(this),
  802. $td = $tr.find('td').eq(i),
  803. index = key.indexOf(' '),
  804. name = key.substring(0, index),
  805. el = key.substring(index + 1),
  806. func = events[key];
  807. $td.find(el).off(name).on(name, function (e) {
  808. var index = $tr.data('index'),
  809. row = that.data[index],
  810. value = row[that.header.fields[i]];
  811. func(e, value, row, index);
  812. });
  813. });
  814. }
  815. });
  816. this.updateSelected();
  817. this.resetView();
  818. };
  819. BootstrapTable.prototype.initServer = function (silent) {
  820. var that = this,
  821. data = {},
  822. params = {
  823. pageSize: this.options.pageSize,
  824. pageNumber: this.options.pageNumber,
  825. searchText: this.searchText,
  826. sortName: this.options.sortName,
  827. sortOrder: this.options.sortOrder
  828. };
  829. if (!this.options.url) {
  830. return;
  831. }
  832. if (!silent) {
  833. this.$loading.show();
  834. }
  835. if (this.options.queryParamsType === 'limit') {
  836. params = {
  837. limit: params.pageSize,
  838. offset: params.pageSize * (params.pageNumber - 1),
  839. search: params.searchText,
  840. sort: params.sortName,
  841. order: params.sortOrder
  842. };
  843. }
  844. data = calculateFunctionValue(this.options.queryParamsType, [params], data);
  845. $.ajax({
  846. type: this.options.method,
  847. url: this.options.url,
  848. data: data,
  849. cache: this.options.cache,
  850. contentType: this.options.contentType,
  851. dataType: 'json',
  852. success: function (res) {
  853. res = calculateFunctionValue(that.options.responseHandler, [res], res);
  854. var data = res;
  855. if (that.options.sidePagination === 'server') {
  856. that.options.totalRows = res.total;
  857. data = res.rows;
  858. }
  859. that.load(data);
  860. that.trigger('load-success', data);
  861. },
  862. error: function (res) {
  863. that.trigger('load-error', res.status);
  864. },
  865. complete: function () {
  866. if (!silent) {
  867. that.$loading.hide();
  868. }
  869. }
  870. });
  871. };
  872. BootstrapTable.prototype.getCaretHtml = function () {
  873. return ['<span class="order' + (this.options.sortOrder === 'desc' ? '' : ' dropup') + '">',
  874. '<span class="caret" style="margin: 10px 5px;"></span>',
  875. '</span>'].join('');
  876. };
  877. BootstrapTable.prototype.updateSelected = function () {
  878. this.$selectItem.each(function () {
  879. $(this).parents('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
  880. });
  881. };
  882. BootstrapTable.prototype.updateRows = function (checked) {
  883. var that = this;
  884. this.$selectItem.each(function () {
  885. that.data[$(this).data('index')][that.header.stateField] = checked;
  886. });
  887. };
  888. BootstrapTable.prototype.resetRows = function () {
  889. var that = this;
  890. $.each(this.data, function (i, row) {
  891. that.$selectAll.prop('checked', false);
  892. that.$selectItem.prop('checked', false);
  893. row[that.header.stateField] = false;
  894. });
  895. };
  896. BootstrapTable.prototype.trigger = function (name) {
  897. var args = Array.prototype.slice.call(arguments, 1);
  898. name += '.bs.table';
  899. this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
  900. this.$el.trigger($.Event(name), args);
  901. this.options.onAll(name, args);
  902. this.$el.trigger($.Event('all.bs.table'), [name, args]);
  903. };
  904. BootstrapTable.prototype.resetHeader = function () {
  905. var that = this,
  906. $fixedHeader = this.$container.find('.fixed-table-header'),
  907. $fixedBody = this.$container.find('.fixed-table-body'),
  908. scrollWidth = this.$el.width() > $fixedBody.width() ? getScrollBarWidth() : 0;
  909. // fix #61: the hidden table reset header bug.
  910. if (this.$el.is(':hidden')) {
  911. clearTimeout(this.timeoutId_); // doesn't matter if it's 0
  912. this.timeoutId_ = setTimeout($.proxy(this.resetHeader, this), 100); // 100ms
  913. return;
  914. }
  915. this.$header_ = this.$header.clone(true);
  916. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
  917. // fix bug: get $el.css('width') error sometime (height = 500)
  918. setTimeout(function () {
  919. $fixedHeader.css({
  920. 'height': '37px',
  921. 'border-bottom': '1px solid #dddddd',
  922. 'margin-right': scrollWidth
  923. }).find('table').css('width', that.$el.css('width'))
  924. .html('').attr('class', that.$el.attr('class'))
  925. .append(that.$header_);
  926. that.$el.css('margin-top', -that.$header.height());
  927. that.$body.find('tr:first-child:not(.no-records-found) > *').each(function(i) {
  928. that.$header_.find('div.fht-cell').eq(i).width($(this).innerWidth());
  929. });
  930. // horizontal scroll event
  931. $fixedBody.off('scroll').on('scroll', function () {
  932. $fixedHeader.scrollLeft($(this).scrollLeft());
  933. });
  934. });
  935. };
  936. BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
  937. if (index === -1) {
  938. return;
  939. }
  940. this.options.columns[index].visible = checked;
  941. this.initHeader();
  942. this.initSearch();
  943. this.initPagination();
  944. this.initBody();
  945. if (this.options.showColumns) {
  946. var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
  947. if (needUpdate) {
  948. $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
  949. }
  950. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  951. $items.filter(':checked').prop('disabled', true);
  952. }
  953. }
  954. };
  955. // PUBLIC FUNCTION DEFINITION
  956. // =======================
  957. BootstrapTable.prototype.resetView = function (params) {
  958. var that = this,
  959. header = this.header;
  960. if (params && params.height) {
  961. this.options.height = params.height;
  962. }
  963. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  964. this.$selectItem.length === this.$selectItem.filter(':checked').length);
  965. if (this.options.height) {
  966. var toolbarHeight = +this.$toolbar.children().outerHeight(true),
  967. paginationHeight = +this.$pagination.children().outerHeight(true),
  968. height = this.options.height - toolbarHeight - paginationHeight;
  969. this.$container.find('.fixed-table-container').css('height', height + 'px');
  970. }
  971. if (this.options.cardView) {
  972. // remove the element css
  973. that.$el.css('margin-top', '0');
  974. that.$container.find('.fixed-table-container').css('padding-bottom', '0');
  975. return;
  976. }
  977. if (this.options.showHeader && this.options.height) {
  978. this.resetHeader();
  979. }
  980. if (this.options.height && this.options.showHeader) {
  981. this.$container.find('.fixed-table-container').css('padding-bottom', '37px');
  982. }
  983. };
  984. BootstrapTable.prototype.getData = function () {
  985. return this.searchText ? this.data : this.options.data;
  986. };
  987. BootstrapTable.prototype.load = function (data) {
  988. this.initData(data);
  989. this.initSearch();
  990. this.initPagination();
  991. this.initBody();
  992. };
  993. BootstrapTable.prototype.append = function (data) {
  994. this.initData(data, true);
  995. this.initSearch();
  996. this.initPagination();
  997. this.initBody(true);
  998. };
  999. BootstrapTable.prototype.remove = function (params) {
  1000. var len = this.options.data.length,
  1001. i, row;
  1002. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  1003. return;
  1004. }
  1005. for (i = len - 1; i >= 0; i--) {
  1006. row = this.options.data[i];
  1007. if (!row.hasOwnProperty(params.field)) {
  1008. return;
  1009. }
  1010. if (params.values.indexOf(row[params.field]) !== -1) {
  1011. this.options.data.splice(i, 1);
  1012. }
  1013. }
  1014. if (len === this.options.data.length) {
  1015. return;
  1016. }
  1017. this.initSearch();
  1018. this.initPagination();
  1019. this.initBody(true);
  1020. };
  1021. BootstrapTable.prototype.updateRow = function (params) {
  1022. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1023. return;
  1024. }
  1025. $.extend(this.data[params.index], params.row);
  1026. this.initBody();
  1027. };
  1028. BootstrapTable.prototype.mergeCells = function (options) {
  1029. var row = options.index,
  1030. col = $.inArray(options.field, this.header.fields),
  1031. rowspan = options.rowspan || 1,
  1032. colspan = options.colspan || 1,
  1033. i, j,
  1034. $tr = this.$body.find('tr'),
  1035. $td = $tr.eq(row).find('td').eq(col);
  1036. if (row < 0 || col < 0 || row >= this.data.length) {
  1037. return;
  1038. }
  1039. for (i = row; i < row + rowspan; i++) {
  1040. for (j = col; j < col + colspan; j++) {
  1041. $tr.eq(i).find('td').eq(j).hide();
  1042. }
  1043. }
  1044. $td.attr('rowspan', rowspan).attr('colspan', colspan)
  1045. .show(10, $.proxy(this.resetView, this));
  1046. };
  1047. BootstrapTable.prototype.getSelections = function () {
  1048. var that = this;
  1049. return $.grep(this.data, function (row) {
  1050. return row[that.header.stateField];
  1051. });
  1052. };
  1053. BootstrapTable.prototype.checkAll = function () {
  1054. this.$selectAll.add(this.$selectAll_).prop('checked', true);
  1055. this.$selectItem.prop('checked', true);
  1056. this.updateRows(true);
  1057. this.updateSelected();
  1058. this.trigger('check-all');
  1059. };
  1060. BootstrapTable.prototype.uncheckAll = function () {
  1061. this.$selectAll.add(this.$selectAll_).prop('checked', false);
  1062. this.$selectItem.prop('checked', false);
  1063. this.updateRows(false);
  1064. this.updateSelected();
  1065. this.trigger('uncheck-all');
  1066. };
  1067. BootstrapTable.prototype.destroy = function () {
  1068. this.$el.insertBefore(this.$container);
  1069. $(this.options.toolbar).insertBefore(this.$el);
  1070. this.$container.next().remove();
  1071. this.$container.remove();
  1072. this.$el.html(this.$el_.html())
  1073. .attr('class', this.$el_.attr('class') || ''); // reset the class
  1074. };
  1075. BootstrapTable.prototype.showLoading = function () {
  1076. this.$loading.show();
  1077. };
  1078. BootstrapTable.prototype.hideLoading = function () {
  1079. this.$loading.hide();
  1080. };
  1081. BootstrapTable.prototype.refresh = function (params) {
  1082. if (params && params.url) {
  1083. this.options.url = params.url;
  1084. }
  1085. this.initServer(params && params.silent);
  1086. };
  1087. BootstrapTable.prototype.showColumn = function (field) {
  1088. this.toggleColumn(getFiledIndex(this.options.columns, field), true, true);
  1089. };
  1090. BootstrapTable.prototype.hideColumn = function (field) {
  1091. this.toggleColumn(getFiledIndex(this.options.columns, field), false, true);
  1092. };
  1093. // BOOTSTRAP TABLE PLUGIN DEFINITION
  1094. // =======================
  1095. $.fn.bootstrapTable = function (option, _relatedTarget) {
  1096. var allowedMethods = [
  1097. 'getSelections', 'getData',
  1098. 'load', 'append', 'remove',
  1099. 'updateRow',
  1100. 'mergeCells',
  1101. 'checkAll', 'uncheckAll',
  1102. 'refresh',
  1103. 'resetView',
  1104. 'destroy',
  1105. 'showLoading', 'hideLoading',
  1106. 'showColumn', 'hideColumn'
  1107. ],
  1108. value;
  1109. this.each(function () {
  1110. var $this = $(this),
  1111. data = $this.data('bootstrap.table'),
  1112. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
  1113. typeof option === 'object' && option);
  1114. if (typeof option === 'string') {
  1115. if ($.inArray(option, allowedMethods) < 0) {
  1116. throw "Unknown method: " + option;
  1117. }
  1118. if (!data) {
  1119. return;
  1120. }
  1121. value = data[option](_relatedTarget);
  1122. if (option === 'destroy') {
  1123. $this.removeData('bootstrap.table');
  1124. }
  1125. }
  1126. if (!data) {
  1127. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  1128. }
  1129. });
  1130. return typeof value === 'undefined' ? this : value;
  1131. };
  1132. $.fn.bootstrapTable.Constructor = BootstrapTable;
  1133. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
  1134. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
  1135. // BOOTSTRAP TABLE INIT
  1136. // =======================
  1137. $(function () {
  1138. $('[data-toggle="table"]').bootstrapTable();
  1139. });
  1140. }(jQuery);