bootstrap-table.js 58 KB

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