bootstrap-table.js 80 KB

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