bootstrap-table.js 57 KB

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