bootstrap-table.js 67 KB

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