bootstrap-table.js 81 KB

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