bootstrap-table.js 87 KB

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