bootstrap-table.js 54 KB

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