bootstrap-table.js 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.6.0
  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. return flag ? str : '';
  24. };
  25. var getPropertyFromOther = function (list, from, to, value) {
  26. var result = '';
  27. $.each(list, function (i, item) {
  28. if (item[from] === value) {
  29. result = item[to];
  30. return false;
  31. }
  32. return true;
  33. });
  34. return result;
  35. };
  36. var getFieldIndex = function (columns, field) {
  37. var index = -1;
  38. $.each(columns, function (i, column) {
  39. if (column.field === field) {
  40. index = i;
  41. return false;
  42. }
  43. return true;
  44. });
  45. return index;
  46. };
  47. var getScrollBarWidth = function () {
  48. var inner = $('<p/>').addClass('fixed-table-scroll-inner'),
  49. outer = $('<div/>').addClass('fixed-table-scroll-outer'),
  50. w1, w2;
  51. outer.append(inner);
  52. $('body').append(outer);
  53. w1 = inner[0].offsetWidth;
  54. outer.css('overflow', 'scroll');
  55. w2 = inner[0].offsetWidth;
  56. if (w1 === w2) {
  57. w2 = outer[0].clientWidth;
  58. }
  59. outer.remove();
  60. return w1 - w2;
  61. };
  62. var calculateObjectValue = function (self, name, args, defaultValue) {
  63. if (typeof name === 'string') {
  64. // support obj.func1.func2
  65. var names = name.split('.');
  66. if (names.length > 1) {
  67. name = window;
  68. $.each(names, function (i, f) {
  69. name = name[f];
  70. });
  71. } else {
  72. name = window[name];
  73. }
  74. }
  75. if (typeof name === 'object') {
  76. return name;
  77. }
  78. if (typeof name === 'function') {
  79. return name.apply(self, args);
  80. }
  81. return defaultValue;
  82. };
  83. var escapeHTML = function (text) {
  84. if (typeof text === 'string') {
  85. return text
  86. .replace(/&/g, "&amp;")
  87. .replace(/</g, "&lt;")
  88. .replace(/>/g, "&gt;")
  89. .replace(/"/g, "&quot;")
  90. .replace(/'/g, "&#039;");
  91. }
  92. return text;
  93. };
  94. // BOOTSTRAP TABLE CLASS DEFINITION
  95. // ======================
  96. var BootstrapTable = function (el, options) {
  97. this.options = options;
  98. this.$el = $(el);
  99. this.$el_ = this.$el.clone();
  100. this.timeoutId_ = 0;
  101. this.init();
  102. };
  103. BootstrapTable.DEFAULTS = {
  104. classes: 'table table-hover',
  105. height: undefined,
  106. undefinedText: '-',
  107. sortName: undefined,
  108. sortOrder: 'asc',
  109. striped: false,
  110. columns: [],
  111. data: [],
  112. method: 'get',
  113. url: undefined,
  114. cache: true,
  115. contentType: 'application/json',
  116. dataType: 'json',
  117. ajaxOptions: {},
  118. queryParams: function (params) {return params;},
  119. queryParamsType: 'limit', // undefined
  120. responseHandler: function (res) {return res;},
  121. pagination: false,
  122. sidePagination: 'client', // client or server
  123. totalRows: 0, // server side need to set
  124. pageNumber: 1,
  125. pageSize: 10,
  126. pageList: [10, 25, 50, 100],
  127. search: false,
  128. searchAlign: 'right',
  129. selectItemName: 'btSelectItem',
  130. showHeader: true,
  131. showColumns: false,
  132. showPaginationSwitch: false,
  133. showRefresh: false,
  134. showToggle: false,
  135. buttonsAlign: 'right',
  136. smartDisplay: true,
  137. minimumCountColumns: 1,
  138. idField: undefined,
  139. cardView: false,
  140. trimOnSearch: true,
  141. clickToSelect: false,
  142. singleSelect: false,
  143. toolbar: undefined,
  144. toolbarAlign: 'left',
  145. checkboxHeader: true,
  146. sortable: true,
  147. maintainSelected: false,
  148. searchTimeOut: 500,
  149. iconSize: undefined,
  150. iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome)
  151. icons: {
  152. paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
  153. paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
  154. refresh: 'glyphicon-refresh icon-refresh',
  155. toggle: 'glyphicon-list-alt icon-list-alt',
  156. columns: 'glyphicon-th icon-th'
  157. },
  158. rowStyle: function (row, index) {return {};},
  159. rowAttributes: function (row, index) {return {};},
  160. onAll: function (name, args) {return false;},
  161. onClickRow: function (item, $element) {return false;},
  162. onDblClickRow: function (item, $element) {return false;},
  163. onSort: function (name, order) {return false;},
  164. onCheck: function (row) {return false;},
  165. onUncheck: function (row) {return false;},
  166. onCheckAll: function () {return false;},
  167. onUncheckAll: function () {return false;},
  168. onLoadSuccess: function (data) {return false;},
  169. onLoadError: function (status) {return false;},
  170. onColumnSwitch: function (field, checked) {return false;},
  171. onPageChange: function (number, size) {return false;},
  172. onSearch: function (text) {return false;},
  173. onPreBody: function (data) {return false;},
  174. onPostBody: function () {return false;},
  175. onPostHeader: function() {return false;}
  176. };
  177. BootstrapTable.LOCALES = [];
  178. BootstrapTable.LOCALES['en-US'] = {
  179. formatLoadingMessage: function () {
  180. return 'Loading, please wait...';
  181. },
  182. formatRecordsPerPage: function (pageNumber) {
  183. return sprintf('%s records per page', pageNumber);
  184. },
  185. formatShowingRows: function (pageFrom, pageTo, totalRows) {
  186. return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows);
  187. },
  188. formatSearch: function () {
  189. return 'Search';
  190. },
  191. formatNoMatches: function () {
  192. return 'No matching records found';
  193. },
  194. formatPaginationSwitch: function () {
  195. return 'Hide/Show pagination';
  196. },
  197. formatRefresh: function () {
  198. return 'Refresh';
  199. },
  200. formatToggle: function () {
  201. return 'Toggle';
  202. },
  203. formatColumns: function () {
  204. return 'Columns';
  205. }
  206. };
  207. $.extend(BootstrapTable.DEFAULTS, BootstrapTable.LOCALES['en-US']);
  208. BootstrapTable.COLUMN_DEFAULTS = {
  209. radio: false,
  210. checkbox: false,
  211. checkboxEnabled: true,
  212. field: undefined,
  213. title: undefined,
  214. 'class': undefined,
  215. align: undefined, // left, right, center
  216. halign: undefined, // left, right, center
  217. valign: undefined, // top, middle, bottom
  218. width: undefined,
  219. sortable: false,
  220. order: 'asc', // asc, desc
  221. visible: true,
  222. switchable: true,
  223. clickToSelect: true,
  224. formatter: undefined,
  225. events: undefined,
  226. sorter: undefined,
  227. cellStyle: undefined,
  228. searchable: true
  229. };
  230. BootstrapTable.EVENTS = {
  231. 'all.bs.table': 'onAll',
  232. 'click-row.bs.table': 'onClickRow',
  233. 'dbl-click-row.bs.table': 'onDblClickRow',
  234. 'sort.bs.table': 'onSort',
  235. 'check.bs.table': 'onCheck',
  236. 'uncheck.bs.table': 'onUncheck',
  237. 'check-all.bs.table': 'onCheckAll',
  238. 'uncheck-all.bs.table': 'onUncheckAll',
  239. 'load-success.bs.table': 'onLoadSuccess',
  240. 'load-error.bs.table': 'onLoadError',
  241. 'column-switch.bs.table': 'onColumnSwitch',
  242. 'page-change.bs.table': 'onPageChange',
  243. 'search.bs.table': 'onSearch',
  244. 'pre-body.bs.table': 'onPreBody',
  245. 'post-body.bs.table': 'onPostBody',
  246. 'post-header.bs.table' : 'onPostHeader'
  247. };
  248. BootstrapTable.prototype.init = function () {
  249. this.initContainer();
  250. this.initTable();
  251. this.initHeader();
  252. this.initData();
  253. this.initToolbar();
  254. this.initPagination();
  255. this.initBody();
  256. this.initServer();
  257. };
  258. BootstrapTable.prototype.initContainer = function () {
  259. this.$container = $([
  260. '<div class="bootstrap-table">',
  261. '<div class="fixed-table-toolbar"></div>',
  262. '<div class="fixed-table-container">',
  263. '<div class="fixed-table-header"><table></table></div>',
  264. '<div class="fixed-table-body">',
  265. '<div class="fixed-table-loading">',
  266. this.options.formatLoadingMessage(),
  267. '</div>',
  268. '</div>',
  269. '<div class="fixed-table-pagination"></div>',
  270. '</div>',
  271. '</div>'].join(''));
  272. this.$container.insertAfter(this.$el);
  273. this.$container.find('.fixed-table-body').append(this.$el);
  274. this.$container.after('<div class="clearfix"></div>');
  275. this.$loading = this.$container.find('.fixed-table-loading');
  276. this.$el.addClass(this.options.classes);
  277. if (this.options.striped) {
  278. this.$el.addClass('table-striped');
  279. }
  280. };
  281. BootstrapTable.prototype.initTable = function () {
  282. var that = this,
  283. columns = [],
  284. data = [];
  285. this.$header = this.$el.find('thead');
  286. if (!this.$header.length) {
  287. this.$header = $('<thead></thead>').appendTo(this.$el);
  288. }
  289. if (!this.$header.find('tr').length) {
  290. this.$header.append('<tr></tr>');
  291. }
  292. this.$header.find('th').each(function () {
  293. var column = $.extend({}, {
  294. title: $(this).html(),
  295. 'class': $(this).attr('class')
  296. }, $(this).data());
  297. columns.push(column);
  298. });
  299. this.options.columns = $.extend([], columns, this.options.columns);
  300. $.each(this.options.columns, function (i, column) {
  301. that.options.columns[i] = $.extend({}, BootstrapTable.COLUMN_DEFAULTS,
  302. {field: i}, column); // when field is undefined, use index instead
  303. });
  304. // if options.data is setting, do not process tbody data
  305. if (this.options.data.length) {
  306. return;
  307. }
  308. this.$el.find('tbody tr').each(function () {
  309. var row = {};
  310. // save tr's id and class
  311. row._id = $(this).attr('id');
  312. row._class = $(this).attr('class');
  313. $(this).find('td').each(function (i) {
  314. var field = that.options.columns[i].field;
  315. row[field] = $(this).html();
  316. // save td's id and class
  317. row['_' + field + '_id'] = $(this).attr('id');
  318. row['_' + field + '_class'] = $(this).attr('class');
  319. row['_' + field + '_data'] = $(this).data();
  320. });
  321. data.push(row);
  322. });
  323. this.options.data = data;
  324. };
  325. BootstrapTable.prototype.initHeader = function () {
  326. var that = this,
  327. visibleColumns = [],
  328. html = [];
  329. this.header = {
  330. fields: [],
  331. styles: [],
  332. classes: [],
  333. formatters: [],
  334. events: [],
  335. sorters: [],
  336. cellStyles: [],
  337. clickToSelects: [],
  338. searchables: []
  339. };
  340. $.each(this.options.columns, function (i, column) {
  341. var text = '',
  342. halign = '', // header align style
  343. align = '', // body align style
  344. style = '',
  345. class_ = sprintf(' class="%s"', column['class']),
  346. order = that.options.sortOrder || column.order,
  347. searchable = true;
  348. if (!column.visible) {
  349. return;
  350. }
  351. halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align);
  352. align = sprintf('text-align: %s; ', column.align);
  353. style = sprintf('vertical-align: %s; ', column.valign);
  354. style += sprintf('width: %spx; ', column.checkbox || column.radio ? 36 : column.width);
  355. visibleColumns.push(column);
  356. that.header.fields.push(column.field);
  357. that.header.styles.push(align + style);
  358. that.header.classes.push(class_);
  359. that.header.formatters.push(column.formatter);
  360. that.header.events.push(column.events);
  361. that.header.sorters.push(column.sorter);
  362. that.header.cellStyles.push(column.cellStyle);
  363. that.header.clickToSelects.push(column.clickToSelect);
  364. that.header.searchables.push(column.searchable);
  365. html.push('<th',
  366. column.checkbox || column.radio ?
  367. sprintf(' class="bs-checkbox %s"', column['class'] || '') :
  368. class_,
  369. sprintf(' style="%s"', halign + style),
  370. '>');
  371. html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ?
  372. 'sortable' : ''));
  373. text = column.title;
  374. if (that.options.sortName === column.field && that.options.sortable && column.sortable) {
  375. text += that.getCaretHtml();
  376. }
  377. if (column.checkbox) {
  378. if (!that.options.singleSelect && that.options.checkboxHeader) {
  379. text = '<input name="btSelectAll" type="checkbox" />';
  380. }
  381. that.header.stateField = column.field;
  382. }
  383. if (column.radio) {
  384. text = '';
  385. that.header.stateField = column.field;
  386. that.options.singleSelect = true;
  387. }
  388. html.push(text);
  389. html.push('</div>');
  390. html.push('<div class="fht-cell"></div>');
  391. html.push('</th>');
  392. });
  393. this.$header.find('tr').html(html.join(''));
  394. this.$header.find('th').each(function (i) {
  395. $(this).data(visibleColumns[i]);
  396. });
  397. this.$container.off('click', 'th').on('click', 'th', function (event) {
  398. if (that.options.sortable && $(this).data().sortable) {
  399. that.onSort(event);
  400. }
  401. });
  402. if (!this.options.showHeader || this.options.cardView) {
  403. this.$header.hide();
  404. this.$container.find('.fixed-table-header').hide();
  405. this.$loading.css('top', 0);
  406. } else {
  407. this.$header.show();
  408. this.$container.find('.fixed-table-header').show();
  409. this.$loading.css('top', '37px');
  410. }
  411. this.$selectAll = this.$header.find('[name="btSelectAll"]');
  412. this.$container.off('click', '[name="btSelectAll"]')
  413. .on('click', '[name="btSelectAll"]', function () {
  414. var checked = $(this).prop('checked');
  415. that[checked ? 'checkAll' : 'uncheckAll']();
  416. });
  417. };
  418. /**
  419. * @param data
  420. * @param type: append / prepend
  421. */
  422. BootstrapTable.prototype.initData = function (data, type) {
  423. if (type === 'append') {
  424. this.data = this.data.concat(data);
  425. } else if (type === 'prepend') {
  426. this.data = [].concat(data).concat(this.data);
  427. } else {
  428. this.data = data || this.options.data;
  429. }
  430. this.options.data = this.data;
  431. if (this.options.sidePagination === 'server') {
  432. return;
  433. }
  434. this.initSort();
  435. };
  436. BootstrapTable.prototype.initSort = function () {
  437. var that = this,
  438. name = this.options.sortName,
  439. order = this.options.sortOrder === 'desc' ? -1 : 1,
  440. index = $.inArray(this.options.sortName, this.header.fields);
  441. if (index !== -1) {
  442. this.data.sort(function (a, b) {
  443. var aa = a[name],
  444. bb = b[name],
  445. value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]);
  446. if (value !== undefined) {
  447. return order * value;
  448. }
  449. if (value !== undefined) {
  450. return order * value;
  451. }
  452. // Fix #161: undefined or null string sort bug.
  453. if (aa === undefined || aa === null) {
  454. aa = '';
  455. }
  456. if (bb === undefined || bb === null) {
  457. bb = '';
  458. }
  459. // IF both values are numeric, do a numeric comparison
  460. if ($.isNumeric(aa) && $.isNumeric(bb)) {
  461. // Convert numerical values form string to float.
  462. aa = parseFloat(aa);
  463. bb = parseFloat(bb);
  464. if (aa < bb) {
  465. return order * -1;
  466. }
  467. return order;
  468. }
  469. if (aa === bb) {
  470. return 0;
  471. }
  472. // If value is not a string, convert to string
  473. if (typeof aa !== 'string')
  474. {
  475. aa = aa.toString();
  476. }
  477. if (aa.localeCompare(bb) === -1) {
  478. return order * -1;
  479. }
  480. return order;
  481. });
  482. }
  483. };
  484. BootstrapTable.prototype.onSort = function (event) {
  485. var $this = $(event.currentTarget),
  486. $this_ = this.$header.find('th').eq($this.index());
  487. this.$header.add(this.$header_).find('span.order').remove();
  488. if (this.options.sortName === $this.data('field')) {
  489. this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc';
  490. } else {
  491. this.options.sortName = $this.data('field');
  492. this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
  493. }
  494. this.trigger('sort', this.options.sortName, this.options.sortOrder);
  495. $this.add($this_).data('order', this.options.sortOrder)
  496. .find('.th-inner').append(this.getCaretHtml());
  497. if (this.options.sidePagination === 'server') {
  498. this.initServer();
  499. return;
  500. }
  501. this.initSort();
  502. this.initBody();
  503. };
  504. BootstrapTable.prototype.initToolbar = function () {
  505. var that = this,
  506. html = [],
  507. timeoutId = 0,
  508. $keepOpen,
  509. $search,
  510. switchableCount = 0;
  511. this.$toolbar = this.$container.find('.fixed-table-toolbar').html('');
  512. if (typeof this.options.toolbar === 'string') {
  513. $(sprintf('<div class="bars pull-%s"></div>', this.options.toolbarAlign))
  514. .appendTo(this.$toolbar)
  515. .append($(this.options.toolbar));
  516. }
  517. // showColumns, showToggle, showRefresh
  518. html = [sprintf('<div class="columns columns-%s btn-group pull-%s">',
  519. this.options.buttonsAlign, this.options.buttonsAlign)];
  520. if (typeof this.options.icons === 'string') {
  521. this.options.icons = calculateObjectValue(null, this.options.icons);
  522. }
  523. if (this.options.showPaginationSwitch) {
  524. html.push(sprintf('<button class="btn btn-default" type="button" name="paginationSwitch" title="%s">',
  525. this.options.formatPaginationSwitch()),
  526. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown),
  527. '</button>');
  528. }
  529. if (this.options.showRefresh) {
  530. html.push(sprintf('<button class="btn btn-default' + (this.options.iconSize == undefined ? '' : ' btn-' + this.options.iconSize) + '" type="button" name="refresh" title="%s">',
  531. this.options.formatRefresh()),
  532. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh),
  533. '</button>');
  534. }
  535. if (this.options.showToggle) {
  536. html.push(sprintf('<button class="btn btn-default' + (this.options.iconSize == undefined ? '' : ' btn-' + this.options.iconSize) + '" type="button" name="toggle" title="%s">',
  537. this.options.formatToggle()),
  538. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggle),
  539. '</button>');
  540. }
  541. if (this.options.showColumns) {
  542. html.push(sprintf('<div class="keep-open btn-group" title="%s">',
  543. this.options.formatColumns()),
  544. '<button type="button" class="btn btn-default' + (this.options.iconSize == undefined ? '' : ' btn-' + this.options.iconSize) + ' dropdown-toggle" data-toggle="dropdown">',
  545. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns),
  546. ' <span class="caret"></span>',
  547. '</button>',
  548. '<ul class="dropdown-menu" role="menu">');
  549. $.each(this.options.columns, function (i, column) {
  550. if (column.radio || column.checkbox) {
  551. return;
  552. }
  553. var checked = column.visible ? ' checked="checked"' : '';
  554. if (column.switchable) {
  555. html.push(sprintf('<li>' +
  556. '<label><input type="checkbox" data-field="%s" value="%s"%s> %s</label>' +
  557. '</li>', column.field, i, checked, column.title));
  558. switchableCount++;
  559. }
  560. });
  561. html.push('</ul>',
  562. '</div>');
  563. }
  564. html.push('</div>');
  565. // Fix #188: this.showToolbar is for extentions
  566. if (this.showToolbar || html.length > 2) {
  567. this.$toolbar.append(html.join(''));
  568. }
  569. if (this.options.showPaginationSwitch) {
  570. this.$toolbar.find('button[name="paginationSwitch"]')
  571. .off('click').on('click', $.proxy(this.togglePagination, this));
  572. }
  573. if (this.options.showRefresh) {
  574. this.$toolbar.find('button[name="refresh"]')
  575. .off('click').on('click', $.proxy(this.refresh, this));
  576. }
  577. if (this.options.showToggle) {
  578. this.$toolbar.find('button[name="toggle"]')
  579. .off('click').on('click', function () {
  580. that.options.cardView = !that.options.cardView;
  581. that.initHeader();
  582. that.initBody();
  583. });
  584. }
  585. if (this.options.showColumns) {
  586. $keepOpen = this.$toolbar.find('.keep-open');
  587. if (switchableCount <= this.options.minimumCountColumns) {
  588. $keepOpen.find('input').prop('disabled', true);
  589. }
  590. $keepOpen.find('li').off('click').on('click', function (event) {
  591. event.stopImmediatePropagation();
  592. });
  593. $keepOpen.find('input').off('click').on('click', function () {
  594. var $this = $(this);
  595. that.toggleColumn($this.val(), $this.prop('checked'), false);
  596. that.trigger('column-switch', $(this).data('field'), $this.prop('checked'));
  597. });
  598. }
  599. if (this.options.search) {
  600. html = [];
  601. html.push(
  602. '<div class="pull-' + this.options.searchAlign + ' search">',
  603. sprintf('<input class="form-control' + (this.options.iconSize == undefined ? '' : ' input-' + this.options.iconSize) + '" type="text" placeholder="%s">',
  604. this.options.formatSearch()),
  605. '</div>');
  606. this.$toolbar.append(html.join(''));
  607. $search = this.$toolbar.find('.search input');
  608. $search.off('keyup').on('keyup', function (event) {
  609. clearTimeout(timeoutId); // doesn't matter if it's 0
  610. timeoutId = setTimeout(function () {
  611. that.onSearch(event);
  612. }, that.options.searchTimeOut);
  613. });
  614. }
  615. };
  616. BootstrapTable.prototype.onSearch = function (event) {
  617. var text = $.trim($(event.currentTarget).val());
  618. // trim search input
  619. if(this.options.trimOnSearch) {
  620. $(event.currentTarget).val(text);
  621. }
  622. if (text === this.searchText) {
  623. return;
  624. }
  625. this.searchText = text;
  626. this.options.pageNumber = 1;
  627. this.initSearch();
  628. this.updatePagination();
  629. this.trigger('search', text);
  630. };
  631. BootstrapTable.prototype.initSearch = function () {
  632. var that = this;
  633. if (this.options.sidePagination !== 'server') {
  634. var s = this.searchText && this.searchText.toLowerCase();
  635. var f = $.isEmptyObject(this.filterColumns) ? null: this.filterColumns;
  636. // Check filter
  637. this.data = f ? $.grep(this.options.data, function (item, i) {
  638. for (var key in f) {
  639. if (item[key] !== f[key]) {
  640. return false;
  641. }
  642. }
  643. return true;
  644. }) : this.options.data;
  645. this.data = s ? $.grep(this.data, function (item, i) {
  646. for (var key in item) {
  647. key = $.isNumeric(key) ? parseInt(key, 10) : key;
  648. var value = item[key];
  649. // Fix #142: search use formated data
  650. value = calculateObjectValue(that.header,
  651. that.header.formatters[$.inArray(key, that.header.fields)],
  652. [value, item, i], value);
  653. var index = $.inArray(key, that.header.fields);
  654. if (index !== -1 && that.header.searchables[index] &&
  655. (typeof value === 'string' ||
  656. typeof value === 'number') &&
  657. (value + '').toLowerCase().indexOf(s) !== -1) {
  658. return true;
  659. }
  660. }
  661. return false;
  662. }) : this.data;
  663. }
  664. };
  665. BootstrapTable.prototype.initPagination = function () {
  666. this.$pagination = this.$container.find('.fixed-table-pagination');
  667. if (!this.options.pagination) {
  668. this.$pagination.hide();
  669. return;
  670. } else {
  671. this.$pagination.show();
  672. }
  673. var that = this,
  674. html = [],
  675. i, from, to,
  676. $pageList,
  677. $first, $pre,
  678. $next, $last,
  679. $number,
  680. data = this.getData();
  681. if (this.options.sidePagination !== 'server') {
  682. this.options.totalRows = data.length;
  683. }
  684. this.totalPages = 0;
  685. if (this.options.totalRows) {
  686. this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
  687. this.options.totalPages = this.totalPages;
  688. }
  689. if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
  690. this.options.pageNumber = this.totalPages;
  691. }
  692. this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
  693. this.pageTo = this.options.pageNumber * this.options.pageSize;
  694. if (this.pageTo > this.options.totalRows) {
  695. this.pageTo = this.options.totalRows;
  696. }
  697. html.push(
  698. '<div class="pull-left pagination-detail">',
  699. '<span class="pagination-info">',
  700. this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
  701. '</span>');
  702. html.push('<span class="page-list">');
  703. var pageNumber = [
  704. '<span class="btn-group dropup">',
  705. '<button type="button" class="btn btn-default '+ (this.options.iconSize == undefined ? '' : ' btn-' + this.options.iconSize)+ ' dropdown-toggle" data-toggle="dropdown">',
  706. '<span class="page-size">',
  707. this.options.pageSize,
  708. '</span>',
  709. ' <span class="caret"></span>',
  710. '</button>',
  711. '<ul class="dropdown-menu" role="menu">'],
  712. pageList = this.options.pageList;
  713. if (typeof this.options.pageList === 'string') {
  714. var list = this.options.pageList.replace('[', '').replace(']', '').replace(/ /g, '').split(',');
  715. pageList = [];
  716. $.each(list, function (i, value) {
  717. pageList.push(+value);
  718. });
  719. }
  720. $.each(pageList, function (i, page) {
  721. if (!that.options.smartDisplay || i === 0 || pageList[i-1] <= that.options.totalRows) {
  722. var active = page === that.options.pageSize ? ' class="active"' : '';
  723. pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page));
  724. }
  725. });
  726. pageNumber.push('</ul></span>');
  727. html.push(this.options.formatRecordsPerPage(pageNumber.join('')));
  728. html.push('</span>');
  729. html.push('</div>',
  730. '<div class="pull-right pagination">',
  731. '<ul class="pagination' + (this.options.iconSize == undefined ? '' : ' pagination-' + this.options.iconSize) + '">',
  732. '<li class="page-first"><a href="javascript:void(0)">&lt;&lt;</a></li>',
  733. '<li class="page-pre"><a href="javascript:void(0)">&lt;</a></li>');
  734. if (this.totalPages < 5) {
  735. from = 1;
  736. to = this.totalPages;
  737. } else {
  738. from = this.options.pageNumber - 2;
  739. to = from + 4;
  740. if (from < 1) {
  741. from = 1;
  742. to = 5;
  743. }
  744. if (to > this.totalPages) {
  745. to = this.totalPages;
  746. from = to - 4;
  747. }
  748. }
  749. for (i = from; i <= to; i++) {
  750. html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
  751. '<a href="javascript:void(0)">', i ,'</a>',
  752. '</li>');
  753. }
  754. html.push(
  755. '<li class="page-next"><a href="javascript:void(0)">&gt;</a></li>',
  756. '<li class="page-last"><a href="javascript:void(0)">&gt;&gt;</a></li>',
  757. '</ul>',
  758. '</div>');
  759. this.$pagination.html(html.join(''));
  760. $pageList = this.$pagination.find('.page-list a');
  761. $first = this.$pagination.find('.page-first');
  762. $pre = this.$pagination.find('.page-pre');
  763. $next = this.$pagination.find('.page-next');
  764. $last = this.$pagination.find('.page-last');
  765. $number = this.$pagination.find('.page-number');
  766. if (this.options.pageNumber <= 1) {
  767. $first.addClass('disabled');
  768. $pre.addClass('disabled');
  769. }
  770. if (this.options.pageNumber >= this.totalPages) {
  771. $next.addClass('disabled');
  772. $last.addClass('disabled');
  773. }
  774. if (this.options.smartDisplay) {
  775. if (this.totalPages <= 1) {
  776. this.$pagination.find('div.pagination').hide();
  777. }
  778. if (this.options.pageList.length < 2 || this.options.totalRows <= this.options.pageList[0]) {
  779. this.$pagination.find('span.page-list').hide();
  780. }
  781. // when data is empty, hide the pagination
  782. this.$pagination[this.getData().length ? 'show' : 'hide']();
  783. }
  784. $pageList.off('click').on('click', $.proxy(this.onPageListChange, this));
  785. $first.off('click').on('click', $.proxy(this.onPageFirst, this));
  786. $pre.off('click').on('click', $.proxy(this.onPagePre, this));
  787. $next.off('click').on('click', $.proxy(this.onPageNext, this));
  788. $last.off('click').on('click', $.proxy(this.onPageLast, this));
  789. $number.off('click').on('click', $.proxy(this.onPageNumber, this));
  790. };
  791. BootstrapTable.prototype.updatePagination = function (event) {
  792. // Fix #171: IE disabled button can be clicked bug.
  793. if (event && $(event.currentTarget).hasClass('disabled')) {
  794. return;
  795. }
  796. if (!this.options.maintainSelected) {
  797. this.resetRows();
  798. }
  799. this.initPagination();
  800. if (this.options.sidePagination === 'server') {
  801. this.initServer();
  802. } else {
  803. this.initBody();
  804. }
  805. this.trigger('page-change', this.options.pageNumber, this.options.pageSize);
  806. };
  807. BootstrapTable.prototype.onPageListChange = function (event) {
  808. var $this = $(event.currentTarget);
  809. $this.parent().addClass('active').siblings().removeClass('active');
  810. this.options.pageSize = +$this.text();
  811. this.$toolbar.find('.page-size').text(this.options.pageSize);
  812. this.updatePagination(event);
  813. };
  814. BootstrapTable.prototype.onPageFirst = function (event) {
  815. this.options.pageNumber = 1;
  816. this.updatePagination(event);
  817. };
  818. BootstrapTable.prototype.onPagePre = function (event) {
  819. this.options.pageNumber--;
  820. this.updatePagination(event);
  821. };
  822. BootstrapTable.prototype.onPageNext = function (event) {
  823. this.options.pageNumber++;
  824. this.updatePagination(event);
  825. };
  826. BootstrapTable.prototype.onPageLast = function (event) {
  827. this.options.pageNumber = this.totalPages;
  828. this.updatePagination(event);
  829. };
  830. BootstrapTable.prototype.onPageNumber = function (event) {
  831. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  832. return;
  833. }
  834. this.options.pageNumber = +$(event.currentTarget).text();
  835. this.updatePagination(event);
  836. };
  837. BootstrapTable.prototype.initBody = function (fixedScroll) {
  838. var that = this,
  839. html = [],
  840. data = this.getData();
  841. this.trigger('pre-body', data);
  842. this.$body = this.$el.find('tbody');
  843. if (!this.$body.length) {
  844. this.$body = $('<tbody></tbody>').appendTo(this.$el);
  845. }
  846. //Fix #389 Bootstrap-table-flatJSON is not working
  847. if (!this.options.pagination || this.options.sidePagination === 'server') {
  848. this.pageFrom = 1;
  849. this.pageTo = data.length;
  850. }
  851. for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
  852. var item = data[i],
  853. style = {},
  854. csses = [],
  855. attributes = {},
  856. htmlAttributes = [];
  857. style = calculateObjectValue(this.options, this.options.rowStyle, [item, i], style);
  858. if (style && style.css) {
  859. for (var key in style.css) {
  860. csses.push(key + ': ' + style.css[key]);
  861. }
  862. }
  863. attributes = calculateObjectValue(this.options,
  864. this.options.rowAttributes, [item, i], attributes);
  865. if (attributes) {
  866. for (var key in attributes) {
  867. htmlAttributes.push(sprintf('%s="%s"', key, escapeHTML(attributes[key])));
  868. }
  869. }
  870. html.push('<tr',
  871. sprintf(' %s', htmlAttributes.join(' ')),
  872. sprintf(' id="%s"', $.isArray(item) ? undefined : item._id),
  873. sprintf(' class="%s"', style.classes || ($.isArray(item) ? undefined : item._class)),
  874. sprintf(' data-index="%s"', i),
  875. '>'
  876. );
  877. if (this.options.cardView) {
  878. html.push(sprintf('<td colspan="%s">', this.header.fields.length));
  879. }
  880. $.each(this.header.fields, function (j, field) {
  881. var text = '',
  882. value = item[field],
  883. type = '',
  884. cellStyle = {},
  885. id_ = '',
  886. class_ = that.header.classes[j],
  887. data_ = '',
  888. column = that.options.columns[getFieldIndex(that.options.columns, field)];
  889. style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
  890. value = calculateObjectValue(that.header,
  891. that.header.formatters[j], [value, item, i], value);
  892. // handle td's id and class
  893. if (item['_' + field + '_id']) {
  894. id_ = sprintf(' id="%s"', item['_' + field + '_id']);
  895. }
  896. if (item['_' + field + '_class']) {
  897. class_ = sprintf(' class="%s"', item['_' + field + '_class']);
  898. }
  899. cellStyle = calculateObjectValue(that.header,
  900. that.header.cellStyles[j], [value, item, i], cellStyle);
  901. if (cellStyle.classes) {
  902. class_ = sprintf(' class="%s"', cellStyle.classes);
  903. }
  904. if (cellStyle.css) {
  905. var csses_ = [];
  906. for (var key in cellStyle.css) {
  907. csses_.push(key + ': ' + cellStyle.css[key]);
  908. }
  909. style = sprintf('style="%s"', csses_.concat(that.header.styles[j]).join('; '));
  910. }
  911. if (item['_' + field + '_data'] && !$.isEmptyObject(item['_' + field + '_data'])) {
  912. $.each(item['_' + field + '_data'], function (k, v) {
  913. // ignore data-index
  914. if (k === 'index') {
  915. return;
  916. }
  917. data_ += sprintf(' data-%s="%s"', k, v);
  918. });
  919. }
  920. if (column.checkbox || column.radio) {
  921. type = column.checkbox ? 'checkbox' : type;
  922. type = column.radio ? 'radio' : type;
  923. text = [that.options.cardView ?
  924. '<div class="card-view">' : '<td class="bs-checkbox">',
  925. '<input' +
  926. sprintf(' data-index="%s"', i) +
  927. sprintf(' name="%s"', that.options.selectItemName) +
  928. sprintf(' type="%s"', type) +
  929. sprintf(' value="%s"', item[that.options.idField]) +
  930. sprintf(' checked="%s"', value === true ||
  931. (value && value.checked) ? 'checked' : undefined) +
  932. sprintf(' disabled="%s"', !column.checkboxEnabled ||
  933. (value && value.disabled) ? 'disabled' : undefined) +
  934. ' />',
  935. that.options.cardView ? '</div>' : '</td>'].join('');
  936. } else {
  937. value = typeof value === 'undefined' || value === null ?
  938. that.options.undefinedText : value;
  939. text = that.options.cardView ?
  940. ['<div class="card-view">',
  941. that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style,
  942. getPropertyFromOther(that.options.columns, 'field', 'title', field)) : '',
  943. sprintf('<span class="value">%s</span>', value),
  944. '</div>'].join('') :
  945. [sprintf('<td%s %s %s %s>', id_, class_, style, data_),
  946. value,
  947. '</td>'].join('');
  948. // Hide empty data on Card view when smartDisplay is set to true.
  949. if (that.options.cardView && that.options.smartDisplay && value === '') {
  950. text = '';
  951. }
  952. }
  953. html.push(text);
  954. });
  955. if (this.options.cardView) {
  956. html.push('</td>');
  957. }
  958. html.push('</tr>');
  959. }
  960. // show no records
  961. if (!html.length) {
  962. html.push('<tr class="no-records-found">',
  963. sprintf('<td colspan="%s">%s</td>', this.header.fields.length, this.options.formatNoMatches()),
  964. '</tr>');
  965. }
  966. this.$body.html(html.join(''));
  967. if (!fixedScroll) {
  968. this.scrollTo(0);
  969. }
  970. // click to select by column
  971. this.$body.find('> tr > td').off('click').on('click', function () {
  972. var $tr = $(this).parent();
  973. that.trigger('click-row', that.data[$tr.data('index')], $tr);
  974. // if click to select - then trigger the checkbox/radio click
  975. if (that.options.clickToSelect) {
  976. if (that.header.clickToSelects[$tr.children().index($(this))]) {
  977. $tr.find(sprintf('[name="%s"]',
  978. that.options.selectItemName))[0].click(); // #144: .trigger('click') bug
  979. }
  980. }
  981. });
  982. this.$body.find('tr').off('dblclick').on('dblclick', function () {
  983. that.trigger('dbl-click-row', that.data[$(this).data('index')], $(this));
  984. });
  985. this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
  986. this.$selectItem.off('click').on('click', function (event) {
  987. event.stopImmediatePropagation();
  988. var checked = $(this).prop('checked'),
  989. row = that.data[$(this).data('index')];
  990. row[that.header.stateField] = checked;
  991. that.trigger(checked ? 'check' : 'uncheck', row);
  992. if (that.options.singleSelect) {
  993. that.$selectItem.not(this).each(function () {
  994. that.data[$(this).data('index')][that.header.stateField] = false;
  995. });
  996. that.$selectItem.filter(':checked').not(this).prop('checked', false);
  997. }
  998. that.updateSelected();
  999. });
  1000. $.each(this.header.events, function (i, events) {
  1001. if (!events) {
  1002. return;
  1003. }
  1004. // fix bug, if events is defined with namespace
  1005. if (typeof events === 'string') {
  1006. events = calculateObjectValue(null, events);
  1007. }
  1008. for (var key in events) {
  1009. that.$body.find('tr').each(function () {
  1010. var $tr = $(this),
  1011. $td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(i),
  1012. index = key.indexOf(' '),
  1013. name = key.substring(0, index),
  1014. el = key.substring(index + 1),
  1015. func = events[key];
  1016. $td.find(el).off(name).on(name, function (e) {
  1017. var index = $tr.data('index'),
  1018. row = that.data[index],
  1019. value = row[that.header.fields[i]];
  1020. func.apply(this, [e, value, row, index]);
  1021. });
  1022. });
  1023. }
  1024. });
  1025. this.updateSelected();
  1026. this.resetView();
  1027. this.trigger('post-body');
  1028. };
  1029. BootstrapTable.prototype.initServer = function (silent, query) {
  1030. var that = this,
  1031. data = {},
  1032. params = {
  1033. pageSize: this.options.pageSize,
  1034. pageNumber: this.options.pageNumber,
  1035. searchText: this.searchText,
  1036. sortName: this.options.sortName,
  1037. sortOrder: this.options.sortOrder
  1038. };
  1039. if (!this.options.url) {
  1040. return;
  1041. }
  1042. if (this.options.queryParamsType === 'limit') {
  1043. params = {
  1044. search: params.searchText,
  1045. sort: params.sortName,
  1046. order: params.sortOrder
  1047. };
  1048. if (this.options.pagination) {
  1049. params.limit = this.options.pageSize;
  1050. params.offset = this.options.pageSize * (this.options.pageNumber - 1);
  1051. }
  1052. }
  1053. data = calculateObjectValue(this.options, this.options.queryParams, [params], data);
  1054. $.extend(data, query || {});
  1055. // false to stop request
  1056. if (data === false) {
  1057. return;
  1058. }
  1059. if (!silent) {
  1060. this.$loading.show();
  1061. }
  1062. $.ajax($.extend({}, calculateObjectValue(null, this.options.ajaxOptions), {
  1063. type: this.options.method,
  1064. url: this.options.url,
  1065. data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
  1066. JSON.stringify(data): data,
  1067. cache: this.options.cache,
  1068. contentType: this.options.contentType,
  1069. dataType: this.options.dataType,
  1070. success: function (res) {
  1071. res = calculateObjectValue(that.options, that.options.responseHandler, [res], res);
  1072. that.load(res);
  1073. that.trigger('load-success', res);
  1074. },
  1075. error: function (res) {
  1076. that.trigger('load-error', res.status);
  1077. },
  1078. complete: function () {
  1079. if (!silent) {
  1080. that.$loading.hide();
  1081. }
  1082. }
  1083. }));
  1084. };
  1085. BootstrapTable.prototype.getCaretHtml = function () {
  1086. return ['<span class="order' + (this.options.sortOrder === 'desc' ? '' : ' dropup') + '">',
  1087. '<span class="caret" style="margin: 10px 5px;"></span>',
  1088. '</span>'].join('');
  1089. };
  1090. BootstrapTable.prototype.updateSelected = function () {
  1091. var checkAll = this.$selectItem.filter(':enabled').length ===
  1092. this.$selectItem.filter(':enabled').filter(':checked').length;
  1093. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll);
  1094. this.$selectItem.each(function () {
  1095. $(this).parents('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
  1096. });
  1097. };
  1098. BootstrapTable.prototype.updateRows = function (checked) {
  1099. var that = this;
  1100. this.$selectItem.each(function () {
  1101. that.data[$(this).data('index')][that.header.stateField] = checked;
  1102. });
  1103. };
  1104. BootstrapTable.prototype.resetRows = function () {
  1105. var that = this;
  1106. $.each(this.data, function (i, row) {
  1107. that.$selectAll.prop('checked', false);
  1108. that.$selectItem.prop('checked', false);
  1109. row[that.header.stateField] = false;
  1110. });
  1111. };
  1112. BootstrapTable.prototype.trigger = function (name) {
  1113. var args = Array.prototype.slice.call(arguments, 1);
  1114. name += '.bs.table';
  1115. this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
  1116. this.$el.trigger($.Event(name), args);
  1117. this.options.onAll(name, args);
  1118. this.$el.trigger($.Event('all.bs.table'), [name, args]);
  1119. };
  1120. BootstrapTable.prototype.resetHeader = function () {
  1121. var that = this,
  1122. $fixedHeader = this.$container.find('.fixed-table-header'),
  1123. $fixedBody = this.$container.find('.fixed-table-body'),
  1124. scrollWidth = this.$el.width() > $fixedBody.width() ? getScrollBarWidth() : 0;
  1125. // fix #61: the hidden table reset header bug.
  1126. if (this.$el.is(':hidden')) {
  1127. clearTimeout(this.timeoutId_); // doesn't matter if it's 0
  1128. this.timeoutId_ = setTimeout($.proxy(this.resetHeader, this), 100); // 100ms
  1129. return;
  1130. }
  1131. this.$header_ = this.$header.clone(true, true);
  1132. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
  1133. // fix bug: get $el.css('width') error sometime (height = 500)
  1134. setTimeout(function () {
  1135. $fixedHeader.css({
  1136. 'height': '37px',
  1137. 'border-bottom': '1px solid #dddddd',
  1138. 'margin-right': scrollWidth
  1139. }).find('table').css('width', that.$el.css('width'))
  1140. .html('').attr('class', that.$el.attr('class'))
  1141. .append(that.$header_);
  1142. // fix bug: $.data() is not working as expected after $.append()
  1143. that.$header.find('th').each(function (i) {
  1144. that.$header_.find('th').eq(i).data($(this).data());
  1145. });
  1146. that.$body.find('tr:first-child:not(.no-records-found) > *').each(function(i) {
  1147. that.$header_.find('div.fht-cell').eq(i).width($(this).innerWidth());
  1148. });
  1149. that.$el.css('margin-top', -that.$header.height());
  1150. // horizontal scroll event
  1151. $fixedBody.off('scroll').on('scroll', function () {
  1152. $fixedHeader.scrollLeft($(this).scrollLeft());
  1153. });
  1154. that.trigger('post-header');
  1155. });
  1156. };
  1157. BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
  1158. if (index === -1) {
  1159. return;
  1160. }
  1161. this.options.columns[index].visible = checked;
  1162. this.initHeader();
  1163. this.initSearch();
  1164. this.initPagination();
  1165. this.initBody();
  1166. if (this.options.showColumns) {
  1167. var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
  1168. if (needUpdate) {
  1169. $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
  1170. }
  1171. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  1172. $items.filter(':checked').prop('disabled', true);
  1173. }
  1174. }
  1175. };
  1176. // PUBLIC FUNCTION DEFINITION
  1177. // =======================
  1178. BootstrapTable.prototype.resetView = function (params) {
  1179. var that = this,
  1180. header = this.header;
  1181. if (params && params.height) {
  1182. this.options.height = params.height;
  1183. }
  1184. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  1185. this.$selectItem.length === this.$selectItem.filter(':checked').length);
  1186. if (this.options.height) {
  1187. var toolbarHeight = +this.$toolbar.children().outerHeight(true),
  1188. paginationHeight = +this.$pagination.children().outerHeight(true),
  1189. height = this.options.height - toolbarHeight - paginationHeight;
  1190. this.$container.find('.fixed-table-container').css('height', height + 'px');
  1191. }
  1192. if (this.options.cardView) {
  1193. // remove the element css
  1194. that.$el.css('margin-top', '0');
  1195. that.$container.find('.fixed-table-container').css('padding-bottom', '0');
  1196. return;
  1197. }
  1198. if (this.options.showHeader && this.options.height) {
  1199. this.resetHeader();
  1200. } else {
  1201. this.trigger('post-header');
  1202. }
  1203. if (this.options.height && this.options.showHeader) {
  1204. this.$container.find('.fixed-table-container').css('padding-bottom', '37px');
  1205. }
  1206. };
  1207. BootstrapTable.prototype.getData = function () {
  1208. return (this.searchText || !$.isEmptyObject(this.filterColumns)) ? this.data : this.options.data;
  1209. };
  1210. BootstrapTable.prototype.load = function (data) {
  1211. var fixedScroll = false;
  1212. // #431: support pagination
  1213. if (this.options.sidePagination === 'server') {
  1214. this.options.totalRows = data.total;
  1215. fixedScroll = data.fixedScroll;
  1216. data = data.rows;
  1217. } else if (!$.isArray(data)) { // support fixedScroll
  1218. fixedScroll = data.fixedScroll;
  1219. data = data.data;
  1220. }
  1221. this.initData(data);
  1222. this.initSearch();
  1223. this.initPagination();
  1224. this.initBody(fixedScroll);
  1225. };
  1226. BootstrapTable.prototype.append = function (data) {
  1227. this.initData(data, 'append');
  1228. this.initSearch();
  1229. this.initPagination();
  1230. this.initBody(true);
  1231. };
  1232. BootstrapTable.prototype.prepend = function (data) {
  1233. this.initData(data, 'prepend');
  1234. this.initSearch();
  1235. this.initPagination();
  1236. this.initBody(true);
  1237. };
  1238. BootstrapTable.prototype.remove = function (params) {
  1239. var len = this.options.data.length,
  1240. i, row;
  1241. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  1242. return;
  1243. }
  1244. for (i = len - 1; i >= 0; i--) {
  1245. row = this.options.data[i];
  1246. if (!row.hasOwnProperty(params.field)) {
  1247. return;
  1248. }
  1249. if ($.inArray(row[params.field], params.values) !== -1) {
  1250. this.options.data.splice(i, 1);
  1251. }
  1252. }
  1253. if (len === this.options.data.length) {
  1254. return;
  1255. }
  1256. this.initSearch();
  1257. this.initPagination();
  1258. this.initBody(true);
  1259. };
  1260. BootstrapTable.prototype.insertRow = function (params) {
  1261. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1262. return;
  1263. }
  1264. this.data.splice(params.index, 0, params.row);
  1265. this.initBody(true);
  1266. };
  1267. BootstrapTable.prototype.updateRow = function (params) {
  1268. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1269. return;
  1270. }
  1271. $.extend(this.data[params.index], params.row);
  1272. this.initBody(true);
  1273. };
  1274. BootstrapTable.prototype.mergeCells = function (options) {
  1275. var row = options.index,
  1276. col = $.inArray(options.field, this.header.fields),
  1277. rowspan = options.rowspan || 1,
  1278. colspan = options.colspan || 1,
  1279. i, j,
  1280. $tr = this.$body.find('tr'),
  1281. $td = $tr.eq(row).find('td').eq(col);
  1282. if (row < 0 || col < 0 || row >= this.data.length) {
  1283. return;
  1284. }
  1285. for (i = row; i < row + rowspan; i++) {
  1286. for (j = col; j < col + colspan; j++) {
  1287. $tr.eq(i).find('td').eq(j).hide();
  1288. }
  1289. }
  1290. $td.attr('rowspan', rowspan).attr('colspan', colspan).show();
  1291. };
  1292. BootstrapTable.prototype.getOptions = function () {
  1293. return this.options;
  1294. };
  1295. BootstrapTable.prototype.getSelections = function () {
  1296. var that = this;
  1297. return $.grep(this.data, function (row) {
  1298. return row[that.header.stateField];
  1299. });
  1300. };
  1301. BootstrapTable.prototype.checkAll = function () {
  1302. this.checkAll_(true);
  1303. };
  1304. BootstrapTable.prototype.uncheckAll = function () {
  1305. this.checkAll_(false);
  1306. };
  1307. BootstrapTable.prototype.checkAll_ = function (checked) {
  1308. var rows;
  1309. if(!checked) {
  1310. rows = this.getSelections();
  1311. }
  1312. this.$selectItem.filter(':enabled').prop('checked', checked);
  1313. this.updateRows(checked);
  1314. this.updateSelected();
  1315. if(checked) {
  1316. rows = this.getSelections();
  1317. }
  1318. this.trigger(checked ? 'check-all' : 'uncheck-all', rows);
  1319. };
  1320. BootstrapTable.prototype.check = function (index) {
  1321. this.check_(true, index);
  1322. };
  1323. BootstrapTable.prototype.uncheck = function (index) {
  1324. this.check_(false, index);
  1325. };
  1326. BootstrapTable.prototype.check_ = function (checked, index) {
  1327. this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  1328. this.data[index][this.header.stateField] = checked;
  1329. this.updateSelected();
  1330. this.trigger(checked ? 'check' : 'uncheck', this.data[index]);
  1331. };
  1332. BootstrapTable.prototype.checkBy = function (obj) {
  1333. this.checkBy_(true, obj);
  1334. };
  1335. BootstrapTable.prototype.uncheckBy = function (obj) {
  1336. this.checkBy_(false, obj);
  1337. };
  1338. BootstrapTable.prototype.checkBy_ = function (checked, obj) {
  1339. if(!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
  1340. return;
  1341. }
  1342. var that = this;
  1343. $.each(this.options.data, function (index, row) {
  1344. if (!row.hasOwnProperty(obj.field)) {
  1345. return false;
  1346. }
  1347. if ($.inArray(row[obj.field], obj.values) !== -1) {
  1348. that.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  1349. row[that.header.stateField] = checked;
  1350. that.trigger(checked ? 'check' : 'uncheck', row);
  1351. }
  1352. });
  1353. this.updateSelected();
  1354. };
  1355. BootstrapTable.prototype.destroy = function () {
  1356. this.$el.insertBefore(this.$container);
  1357. $(this.options.toolbar).insertBefore(this.$el);
  1358. this.$container.next().remove();
  1359. this.$container.remove();
  1360. this.$el.html(this.$el_.html())
  1361. .css('margin-top', '0')
  1362. .attr('class', this.$el_.attr('class') || ''); // reset the class
  1363. };
  1364. BootstrapTable.prototype.showLoading = function () {
  1365. this.$loading.show();
  1366. };
  1367. BootstrapTable.prototype.hideLoading = function () {
  1368. this.$loading.hide();
  1369. };
  1370. BootstrapTable.prototype.togglePagination = function () {
  1371. this.options.pagination = !this.options.pagination;
  1372. var button = this.$toolbar.find('button[name="paginationSwitch"] i');
  1373. if (this.options.pagination) {
  1374. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown);
  1375. } else {
  1376. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp);
  1377. }
  1378. this.updatePagination();
  1379. };
  1380. BootstrapTable.prototype.refresh = function (params) {
  1381. if (params && params.url) {
  1382. this.options.url = params.url;
  1383. this.options.pageNumber = 1;
  1384. }
  1385. this.initServer(params && params.silent, params && params.query);
  1386. };
  1387. BootstrapTable.prototype.showColumn = function (field) {
  1388. this.toggleColumn(getFieldIndex(this.options.columns, field), true, true);
  1389. };
  1390. BootstrapTable.prototype.hideColumn = function (field) {
  1391. this.toggleColumn(getFieldIndex(this.options.columns, field), false, true);
  1392. };
  1393. BootstrapTable.prototype.filterBy = function (columns) {
  1394. this.filterColumns = $.isEmptyObject(columns) ? {}: columns;
  1395. this.options.pageNumber = 1;
  1396. this.initSearch();
  1397. this.updatePagination();
  1398. };
  1399. BootstrapTable.prototype.scrollTo = function (value) {
  1400. var $tbody = this.$container.find('.fixed-table-body');
  1401. if (typeof value === 'string') {
  1402. value = value === 'bottom' ? $tbody[0].scrollHeight : 0;
  1403. }
  1404. if (typeof value === 'number') {
  1405. $tbody.scrollTop(value);
  1406. }
  1407. };
  1408. BootstrapTable.prototype.selectPage = function (page) {
  1409. if (page > 0 && page <= this.options.totalPages) {
  1410. this.options.pageNumber = page;
  1411. this.updatePagination();
  1412. }
  1413. };
  1414. BootstrapTable.prototype.prevPage = function () {
  1415. if (this.options.pageNumber > 1) {
  1416. this.options.pageNumber--;
  1417. this.updatePagination();
  1418. }
  1419. };
  1420. BootstrapTable.prototype.nextPage = function () {
  1421. if (this.options.pageNumber < this.options.totalPages) {
  1422. this.options.pageNumber++;
  1423. this.updatePagination();
  1424. }
  1425. };
  1426. BootstrapTable.prototype.toggleView = function () {
  1427. this.options.cardView = !this.options.cardView;
  1428. this.initHeader();
  1429. this.initBody();
  1430. };
  1431. // BOOTSTRAP TABLE PLUGIN DEFINITION
  1432. // =======================
  1433. var allowedMethods = [
  1434. 'getOptions',
  1435. 'getSelections', 'getData',
  1436. 'load', 'append', 'prepend', 'remove',
  1437. 'insertRow', 'updateRow',
  1438. 'mergeCells',
  1439. 'checkAll', 'uncheckAll',
  1440. 'check', 'uncheck',
  1441. 'checkBy', 'uncheckBy',
  1442. 'refresh',
  1443. 'resetView',
  1444. 'destroy',
  1445. 'showLoading', 'hideLoading',
  1446. 'showColumn', 'hideColumn',
  1447. 'filterBy',
  1448. 'scrollTo',
  1449. 'selectPage', 'prevPage', 'nextPage',
  1450. 'togglePagination',
  1451. 'toggleView'
  1452. ];
  1453. $.fn.bootstrapTable = function (option, _relatedTarget) {
  1454. var value;
  1455. this.each(function () {
  1456. var $this = $(this),
  1457. data = $this.data('bootstrap.table'),
  1458. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
  1459. typeof option === 'object' && option);
  1460. if (typeof option === 'string') {
  1461. if ($.inArray(option, allowedMethods) < 0) {
  1462. throw "Unknown method: " + option;
  1463. }
  1464. if (!data) {
  1465. return;
  1466. }
  1467. value = data[option](_relatedTarget);
  1468. if (option === 'destroy') {
  1469. $this.removeData('bootstrap.table');
  1470. }
  1471. }
  1472. if (!data) {
  1473. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  1474. }
  1475. });
  1476. return typeof value === 'undefined' ? this : value;
  1477. };
  1478. $.fn.bootstrapTable.Constructor = BootstrapTable;
  1479. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
  1480. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
  1481. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES;
  1482. $.fn.bootstrapTable.methods = allowedMethods;
  1483. // BOOTSTRAP TABLE INIT
  1484. // =======================
  1485. $(function () {
  1486. $('[data-toggle="table"]').bootstrapTable();
  1487. });
  1488. }(jQuery);