bootstrap-table.js 82 KB

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