bootstrap-table.js 58 KB

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