bootstrap-table.js 68 KB

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