bootstrap-table.js 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506
  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. sprintf(' checked="%s"', value === true ||
  1290. (value && value.checked) ? 'checked' : undefined) +
  1291. sprintf(' disabled="%s"', !column.checkboxEnabled ||
  1292. (value && value.disabled) ? 'disabled' : undefined) +
  1293. ' />',
  1294. that.options.cardView ? '</div>' : '</td>'
  1295. ].join('');
  1296. item[that.header.stateField] = value === true || (value && value.checked);
  1297. } else {
  1298. value = typeof value === 'undefined' || value === null ?
  1299. that.options.undefinedText : value;
  1300. text = that.options.cardView ? ['<div class="card-view">',
  1301. that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style,
  1302. getPropertyFromOther(that.columns, 'field', 'title', field)) : '',
  1303. sprintf('<span class="value">%s</span>', value),
  1304. '</div>'
  1305. ].join('') : [sprintf('<td%s %s %s %s %s %s>', id_, class_, style, data_, rowspan_, title_),
  1306. value,
  1307. '</td>'
  1308. ].join('');
  1309. // Hide empty data on Card view when smartDisplay is set to true.
  1310. if (that.options.cardView && that.options.smartDisplay && value === '') {
  1311. text = '';
  1312. }
  1313. }
  1314. html.push(text);
  1315. });
  1316. if (this.options.cardView) {
  1317. html.push('</td>');
  1318. }
  1319. html.push('</tr>');
  1320. }
  1321. // show no records
  1322. if (!html.length) {
  1323. html.push('<tr class="no-records-found">',
  1324. sprintf('<td colspan="%s">%s</td>',
  1325. this.$header.find('th').length, this.options.formatNoMatches()),
  1326. '</tr>');
  1327. }
  1328. this.$body.html(html.join(''));
  1329. if (!fixedScroll) {
  1330. this.scrollTo(0);
  1331. }
  1332. // click to select by column
  1333. this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', function (e) {
  1334. var $td = $(this),
  1335. $tr = $td.parent(),
  1336. item = that.data[$tr.data('index')],
  1337. index = $td[0].cellIndex,
  1338. field = that.header.fields[that.options.detailView && !that.options.cardView ? index - 1 : index],
  1339. colomn = that.columns[getFieldIndex(that.columns, field)],
  1340. value = item[field];
  1341. if ($td.find('.detail-icon').length) {
  1342. return;
  1343. }
  1344. that.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td);
  1345. that.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr);
  1346. // if click to select - then trigger the checkbox/radio click
  1347. if (e.type === 'click' && that.options.clickToSelect && colomn.clickToSelect) {
  1348. var $selectItem = $tr.find(sprintf('[name="%s"]', that.options.selectItemName));
  1349. if ($selectItem.length) {
  1350. $selectItem[0].click(); // #144: .trigger('click') bug
  1351. }
  1352. }
  1353. });
  1354. this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', function () {
  1355. var $this = $(this),
  1356. $tr = $this.parent().parent(),
  1357. index = $tr.data('index'),
  1358. row = data[index]; // Fix #980 Detail view, when searching, returns wrong row
  1359. // remove and update
  1360. if ($tr.next().is('tr.detail-view')) {
  1361. $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailOpen));
  1362. $tr.next().remove();
  1363. that.trigger('collapse-row', index, row);
  1364. } else {
  1365. $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailClose));
  1366. $tr.after(sprintf('<tr class="detail-view"><td colspan="%s">%s</td></tr>',
  1367. $tr.find('td').length, calculateObjectValue(that.options,
  1368. that.options.detailFormatter, [index, row], '')));
  1369. that.trigger('expand-row', index, row, $tr.next().find('td'));
  1370. }
  1371. that.resetView();
  1372. });
  1373. this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
  1374. this.$selectItem.off('click').on('click', function (event) {
  1375. event.stopImmediatePropagation();
  1376. var checked = $(this).prop('checked'),
  1377. row = that.data[$(this).data('index')];
  1378. row[that.header.stateField] = checked;
  1379. if (that.options.singleSelect) {
  1380. that.$selectItem.not(this).each(function () {
  1381. that.data[$(this).data('index')][that.header.stateField] = false;
  1382. });
  1383. that.$selectItem.filter(':checked').not(this).prop('checked', false);
  1384. }
  1385. that.updateSelected();
  1386. that.trigger(checked ? 'check' : 'uncheck', row);
  1387. });
  1388. $.each(this.header.events, function (i, events) {
  1389. if (!events) {
  1390. return;
  1391. }
  1392. // fix bug, if events is defined with namespace
  1393. if (typeof events === 'string') {
  1394. events = calculateObjectValue(null, events);
  1395. }
  1396. var field = that.header.fields[i],
  1397. fieldIndex = $.inArray(field, that.getVisibleFields());
  1398. if (that.options.detailView && !that.options.cardView) {
  1399. fieldIndex += 1;
  1400. }
  1401. for (var key in events) {
  1402. that.$body.find('tr').each(function () {
  1403. var $tr = $(this),
  1404. $td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(fieldIndex),
  1405. index = key.indexOf(' '),
  1406. name = key.substring(0, index),
  1407. el = key.substring(index + 1),
  1408. func = events[key];
  1409. $td.find(el).off(name).on(name, function (e) {
  1410. var index = $tr.data('index'),
  1411. row = that.data[index],
  1412. value = row[field];
  1413. func.apply(this, [e, value, row, index]);
  1414. });
  1415. });
  1416. }
  1417. });
  1418. this.updateSelected();
  1419. this.resetView();
  1420. this.trigger('post-body');
  1421. };
  1422. BootstrapTable.prototype.initServer = function (silent, query) {
  1423. var that = this,
  1424. data = {},
  1425. params = {
  1426. pageSize: this.options.pageSize === this.options.formatAllRows() ?
  1427. this.options.totalRows : this.options.pageSize,
  1428. pageNumber: this.options.pageNumber,
  1429. searchText: this.searchText,
  1430. sortName: this.options.sortName,
  1431. sortOrder: this.options.sortOrder
  1432. },
  1433. request;
  1434. if (!this.options.url && !this.options.ajax) {
  1435. return;
  1436. }
  1437. if (this.options.queryParamsType === 'limit') {
  1438. params = {
  1439. search: params.searchText,
  1440. sort: params.sortName,
  1441. order: params.sortOrder
  1442. };
  1443. if (this.options.pagination) {
  1444. params.limit = this.options.pageSize === this.options.formatAllRows() ?
  1445. this.options.totalRows : this.options.pageSize;
  1446. params.offset = this.options.pageSize === this.options.formatAllRows() ?
  1447. 0 : this.options.pageSize * (this.options.pageNumber - 1);
  1448. }
  1449. }
  1450. if (!($.isEmptyObject(this.filterColumnsPartial))) {
  1451. params['filter'] = JSON.stringify(this.filterColumnsPartial, null);
  1452. }
  1453. data = calculateObjectValue(this.options, this.options.queryParams, [params], data);
  1454. $.extend(data, query || {});
  1455. // false to stop request
  1456. if (data === false) {
  1457. return;
  1458. }
  1459. if (!silent) {
  1460. this.$tableLoading.show();
  1461. }
  1462. request = $.extend({}, calculateObjectValue(null, this.options.ajaxOptions), {
  1463. type: this.options.method,
  1464. url: this.options.url,
  1465. data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
  1466. JSON.stringify(data) : data,
  1467. cache: this.options.cache,
  1468. contentType: this.options.contentType,
  1469. dataType: this.options.dataType,
  1470. success: function (res) {
  1471. res = calculateObjectValue(that.options, that.options.responseHandler, [res], res);
  1472. that.load(res);
  1473. that.trigger('load-success', res);
  1474. },
  1475. error: function (res) {
  1476. that.trigger('load-error', res.status);
  1477. },
  1478. complete: function () {
  1479. if (!silent) {
  1480. that.$tableLoading.hide();
  1481. }
  1482. }
  1483. });
  1484. if (this.options.ajax) {
  1485. calculateObjectValue(this, this.options.ajax, [request], null);
  1486. } else {
  1487. $.ajax(request);
  1488. }
  1489. };
  1490. BootstrapTable.prototype.getCaret = function () {
  1491. var that = this;
  1492. $.each(this.$header.find('th'), function (i, th) {
  1493. $(th).find('.sortable').removeClass('desc asc').addClass($(th).data('field') === that.options.sortName ? that.options.sortOrder : 'both');
  1494. });
  1495. };
  1496. BootstrapTable.prototype.updateSelected = function () {
  1497. var checkAll = this.$selectItem.filter(':enabled').length ===
  1498. this.$selectItem.filter(':enabled').filter(':checked').length;
  1499. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll);
  1500. this.$selectItem.each(function () {
  1501. $(this).closest('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
  1502. });
  1503. };
  1504. BootstrapTable.prototype.updateRows = function () {
  1505. var that = this;
  1506. this.$selectItem.each(function () {
  1507. that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked');
  1508. });
  1509. };
  1510. BootstrapTable.prototype.resetRows = function () {
  1511. var that = this;
  1512. $.each(this.data, function (i, row) {
  1513. that.$selectAll.prop('checked', false);
  1514. that.$selectItem.prop('checked', false);
  1515. if (that.header.stateField) {
  1516. row[that.header.stateField] = false;
  1517. }
  1518. });
  1519. };
  1520. BootstrapTable.prototype.trigger = function (name) {
  1521. var args = Array.prototype.slice.call(arguments, 1);
  1522. name += '.bs.table';
  1523. this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
  1524. this.$el.trigger($.Event(name), args);
  1525. this.options.onAll(name, args);
  1526. this.$el.trigger($.Event('all.bs.table'), [name, args]);
  1527. };
  1528. BootstrapTable.prototype.resetHeader = function () {
  1529. // fix #61: the hidden table reset header bug.
  1530. // fix bug: get $el.css('width') error sometime (height = 500)
  1531. clearTimeout(this.timeoutId_);
  1532. this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0);
  1533. };
  1534. BootstrapTable.prototype.fitHeader = function () {
  1535. var that = this,
  1536. fixedBody,
  1537. scrollWidth;
  1538. if (that.$el.is(':hidden')) {
  1539. that.timeoutId_ = setTimeout($.proxy(that.fitHeader, that), 100);
  1540. return;
  1541. }
  1542. fixedBody = this.$tableBody.get(0);
  1543. scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
  1544. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
  1545. getScrollBarWidth() : 0;
  1546. this.$el.css('margin-top', -this.$header.outerHeight());
  1547. this.$header_ = this.$header.clone(true, true);
  1548. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
  1549. this.$tableHeader.css({
  1550. 'margin-right': scrollWidth
  1551. }).find('table').css('width', this.$el.outerWidth())
  1552. .html('').attr('class', this.$el.attr('class'))
  1553. .append(this.$header_);
  1554. // fix bug: $.data() is not working as expected after $.append()
  1555. this.$header.find('th[data-field]').each(function (i) {
  1556. that.$header_.find(sprintf('th[data-field="%s"]', $(this).data('field'))).data($(this).data());
  1557. });
  1558. var visibleFields = this.getVisibleFields();
  1559. this.$body.find('tr:first-child:not(.no-records-found) > *').each(function (i) {
  1560. var $this = $(this),
  1561. index = i;
  1562. if (that.options.detailView && !that.options.cardView) {
  1563. if (i === 0) {
  1564. that.$header_.find('th.detail').find('.fht-cell').width($this.innerWidth());
  1565. }
  1566. index = i - 1;
  1567. }
  1568. that.$header_.find(sprintf('th[data-field="%s"]', visibleFields[index]))
  1569. .find('.fht-cell').width($this.innerWidth());
  1570. });
  1571. // horizontal scroll event
  1572. // TODO: it's probably better improving the layout than binding to scroll event
  1573. this.$tableBody.off('scroll').on('scroll', function () {
  1574. that.$tableHeader.scrollLeft($(this).scrollLeft());
  1575. if (that.options.showFooter && !that.options.cardView) {
  1576. that.$tableFooter.scrollLeft($(this).scrollLeft());
  1577. }
  1578. });
  1579. that.trigger('post-header');
  1580. };
  1581. BootstrapTable.prototype.resetFooter = function () {
  1582. var that = this,
  1583. data = that.getData(),
  1584. html = [];
  1585. if (!this.options.showFooter || this.options.cardView) { //do nothing
  1586. return;
  1587. }
  1588. if (!this.options.cardView && this.options.detailView) {
  1589. html.push('<td><div class="th-inner">&nbsp;</div><div class="fht-cell"></div></td>');
  1590. }
  1591. $.each(this.columns, function (i, column) {
  1592. var falign = '', // footer align style
  1593. style = '',
  1594. class_ = sprintf(' class="%s"', column['class']);
  1595. if (!column.visible) {
  1596. return;
  1597. }
  1598. if (that.options.cardView && (!column.cardVisible)) {
  1599. return;
  1600. }
  1601. falign = sprintf('text-align: %s; ', column.falign ? column.falign : column.align);
  1602. style = sprintf('vertical-align: %s; ', column.valign);
  1603. html.push('<td', class_, sprintf(' style="%s"', falign + style), '>');
  1604. html.push('<div class="th-inner">');
  1605. html.push(calculateObjectValue(column, column.footerFormatter, [data], '&nbsp;') || '&nbsp;');
  1606. html.push('</div>');
  1607. html.push('<div class="fht-cell"></div>');
  1608. html.push('</div>');
  1609. html.push('</td>');
  1610. });
  1611. this.$tableFooter.find('tr').html(html.join(''));
  1612. clearTimeout(this.timeoutFooter_);
  1613. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this),
  1614. this.$el.is(':hidden') ? 100 : 0);
  1615. };
  1616. BootstrapTable.prototype.fitFooter = function () {
  1617. var that = this,
  1618. $footerTd,
  1619. elWidth,
  1620. scrollWidth;
  1621. clearTimeout(this.timeoutFooter_);
  1622. if (this.$el.is(':hidden')) {
  1623. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100);
  1624. return;
  1625. }
  1626. elWidth = this.$el.css('width');
  1627. scrollWidth = elWidth > this.$tableBody.width() ? getScrollBarWidth() : 0;
  1628. this.$tableFooter.css({
  1629. 'margin-right': scrollWidth
  1630. }).find('table').css('width', elWidth)
  1631. .attr('class', this.$el.attr('class'));
  1632. $footerTd = this.$tableFooter.find('td');
  1633. this.$body.find('tr:first-child:not(.no-records-found) > *').each(function (i) {
  1634. var $this = $(this);
  1635. $footerTd.eq(i).find('.fht-cell').width($this.innerWidth());
  1636. });
  1637. };
  1638. BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
  1639. if (index === -1) {
  1640. return;
  1641. }
  1642. this.columns[index].visible = checked;
  1643. this.initHeader();
  1644. this.initSearch();
  1645. this.initPagination();
  1646. this.initBody();
  1647. if (this.options.showColumns) {
  1648. var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
  1649. if (needUpdate) {
  1650. $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
  1651. }
  1652. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  1653. $items.filter(':checked').prop('disabled', true);
  1654. }
  1655. }
  1656. };
  1657. BootstrapTable.prototype.toggleRow = function (index, isIdField, visible) {
  1658. if (index === -1) {
  1659. return;
  1660. }
  1661. $(this.$body[0]).children().filter(sprintf(isIdField ? '[data-uniqueid="%s"]' : '[data-index="%s"]', index))[visible ? 'show' : 'hide']();
  1662. };
  1663. BootstrapTable.prototype.getVisibleFields = function () {
  1664. var that = this,
  1665. visibleFields = [];
  1666. $.each(this.header.fields, function (j, field) {
  1667. var column = that.columns[getFieldIndex(that.columns, field)];
  1668. if (!column.visible) {
  1669. return;
  1670. }
  1671. visibleFields.push(field);
  1672. });
  1673. return visibleFields;
  1674. };
  1675. // PUBLIC FUNCTION DEFINITION
  1676. // =======================
  1677. BootstrapTable.prototype.resetView = function (params) {
  1678. var padding = 0;
  1679. if (params && params.height) {
  1680. this.options.height = params.height;
  1681. }
  1682. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  1683. this.$selectItem.length === this.$selectItem.filter(':checked').length);
  1684. if (this.options.height) {
  1685. var toolbarHeight = getRealHeight(this.$toolbar),
  1686. paginationHeight = getRealHeight(this.$pagination),
  1687. height = this.options.height - toolbarHeight - paginationHeight;
  1688. this.$tableContainer.css('height', height + 'px');
  1689. }
  1690. if (this.options.cardView) {
  1691. // remove the element css
  1692. this.$el.css('margin-top', '0');
  1693. this.$tableContainer.css('padding-bottom', '0');
  1694. return;
  1695. }
  1696. if (this.options.showHeader && this.options.height) {
  1697. this.$tableHeader.show();
  1698. this.resetHeader();
  1699. padding += this.$header.outerHeight();
  1700. } else {
  1701. this.$tableHeader.hide();
  1702. this.trigger('post-header');
  1703. }
  1704. if (this.options.showFooter) {
  1705. this.resetFooter();
  1706. if (this.options.height) {
  1707. padding += this.$tableFooter.outerHeight() + 1;
  1708. }
  1709. }
  1710. // Assign the correct sortable arrow
  1711. this.getCaret();
  1712. this.$tableContainer.css('padding-bottom', padding + 'px');
  1713. this.trigger('reset-view');
  1714. };
  1715. BootstrapTable.prototype.getData = function (useCurrentPage) {
  1716. return (this.searchText || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) ?
  1717. (useCurrentPage ? this.data.slice(this.pageFrom - 1, this.pageTo) : this.data) :
  1718. (useCurrentPage ? this.options.data.slice(this.pageFrom - 1, this.pageTo) : this.options.data);
  1719. };
  1720. BootstrapTable.prototype.load = function (data) {
  1721. var fixedScroll = false;
  1722. // #431: support pagination
  1723. if (this.options.sidePagination === 'server') {
  1724. this.options.totalRows = data.total;
  1725. fixedScroll = data.fixedScroll;
  1726. data = data.rows;
  1727. } else if (!$.isArray(data)) { // support fixedScroll
  1728. fixedScroll = data.fixedScroll;
  1729. data = data.data;
  1730. }
  1731. this.initData(data);
  1732. this.initSearch();
  1733. this.initPagination();
  1734. this.initBody(fixedScroll);
  1735. };
  1736. BootstrapTable.prototype.append = function (data) {
  1737. this.initData(data, 'append');
  1738. this.initSearch();
  1739. this.initPagination();
  1740. this.initBody(true);
  1741. };
  1742. BootstrapTable.prototype.prepend = function (data) {
  1743. this.initData(data, 'prepend');
  1744. this.initSearch();
  1745. this.initPagination();
  1746. this.initBody(true);
  1747. };
  1748. BootstrapTable.prototype.remove = function (params) {
  1749. var len = this.options.data.length,
  1750. i, row;
  1751. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  1752. return;
  1753. }
  1754. for (i = len - 1; i >= 0; i--) {
  1755. row = this.options.data[i];
  1756. if (!row.hasOwnProperty(params.field)) {
  1757. continue;
  1758. }
  1759. if ($.inArray(row[params.field], params.values) !== -1) {
  1760. this.options.data.splice(i, 1);
  1761. }
  1762. }
  1763. if (len === this.options.data.length) {
  1764. return;
  1765. }
  1766. this.initSearch();
  1767. this.initPagination();
  1768. this.initBody(true);
  1769. };
  1770. BootstrapTable.prototype.removeAll = function () {
  1771. if (this.options.data.length > 0) {
  1772. this.options.data.splice(0, this.options.data.length);
  1773. this.initSearch();
  1774. this.initPagination();
  1775. this.initBody(true);
  1776. }
  1777. };
  1778. BootstrapTable.prototype.getRowByUniqueId = function (id) {
  1779. var uniqueId = this.options.uniqueId,
  1780. len = this.options.data.length,
  1781. dataRow = null,
  1782. i, row;
  1783. for (i = len - 1; i >= 0; i--) {
  1784. row = this.options.data[i];
  1785. if (!row.hasOwnProperty(uniqueId)) {
  1786. continue;
  1787. }
  1788. if (typeof row[uniqueId] === 'string') {
  1789. id = id.toString();
  1790. } else if (typeof row[uniqueId] === 'number') {
  1791. if ((Number(row[uniqueId]) === row[uniqueId]) && (row[uniqueId] % 1 === 0)) {
  1792. id = parseInt(id);
  1793. } else if ((row[uniqueId] === Number(row[uniqueId])) && (row[uniqueId] !== 0)) {
  1794. id = parseFloat(id);
  1795. }
  1796. }
  1797. if (row[uniqueId] === id) {
  1798. dataRow = row;
  1799. break;
  1800. }
  1801. }
  1802. return dataRow;
  1803. };
  1804. BootstrapTable.prototype.removeByUniqueId = function (id) {
  1805. var len = this.options.data.length,
  1806. row = this.getRowByUniqueId(id);
  1807. if (row) {
  1808. this.options.data.splice(this.options.data.indexOf(row), 1);
  1809. }
  1810. if (len === this.options.data.length) {
  1811. return;
  1812. }
  1813. this.initSearch();
  1814. this.initPagination();
  1815. this.initBody(true);
  1816. };
  1817. BootstrapTable.prototype.insertRow = function (params) {
  1818. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1819. return;
  1820. }
  1821. this.data.splice(params.index, 0, params.row);
  1822. this.initSearch();
  1823. this.initPagination();
  1824. this.initSort();
  1825. this.initBody(true);
  1826. };
  1827. BootstrapTable.prototype.updateRow = function (params) {
  1828. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  1829. return;
  1830. }
  1831. $.extend(this.data[params.index], params.row);
  1832. this.initSort();
  1833. this.initBody(true);
  1834. };
  1835. BootstrapTable.prototype.showRow = function (params) {
  1836. if (!params.hasOwnProperty('index')) {
  1837. return;
  1838. }
  1839. this.toggleRow(params.index, params.isIdField === undefined ? false : true, true);
  1840. };
  1841. BootstrapTable.prototype.hideRow = function (params) {
  1842. if (!params.hasOwnProperty('index')) {
  1843. return;
  1844. }
  1845. this.toggleRow(params.index, params.isIdField === undefined ? false : true, false);
  1846. };
  1847. BootstrapTable.prototype.getRowsHidden = function (show) {
  1848. var rows = $(this.$body[0]).children().filter(':hidden'),
  1849. i = 0;
  1850. if (show) {
  1851. for (; i < rows.length; i++) {
  1852. $(rows[i]).show();
  1853. }
  1854. }
  1855. return rows;
  1856. };
  1857. BootstrapTable.prototype.mergeCells = function (options) {
  1858. var row = options.index,
  1859. col = $.inArray(options.field, this.getVisibleFields()),
  1860. rowspan = options.rowspan || 1,
  1861. colspan = options.colspan || 1,
  1862. i, j,
  1863. $tr = this.$body.find('tr'),
  1864. $td;
  1865. if (this.options.detailView && !this.options.cardView) {
  1866. col += 1;
  1867. }
  1868. $td = $tr.eq(row).find('td').eq(col);
  1869. if (row < 0 || col < 0 || row >= this.data.length) {
  1870. return;
  1871. }
  1872. for (i = row; i < row + rowspan; i++) {
  1873. for (j = col; j < col + colspan; j++) {
  1874. $tr.eq(i).find('td').eq(j).hide();
  1875. }
  1876. }
  1877. $td.attr('rowspan', rowspan).attr('colspan', colspan).show();
  1878. };
  1879. BootstrapTable.prototype.updateCell = function (params) {
  1880. if (!params.hasOwnProperty('rowIndex') || !params.hasOwnProperty('fieldName') || !params.hasOwnProperty('fieldValue')) {
  1881. return;
  1882. }
  1883. this.data[params.rowIndex][params.fieldName] = params.fieldValue;
  1884. this.initSort();
  1885. this.initBody(true);
  1886. };
  1887. BootstrapTable.prototype.getOptions = function () {
  1888. return this.options;
  1889. };
  1890. BootstrapTable.prototype.getSelections = function () {
  1891. var that = this;
  1892. return $.grep(this.data, function (row) {
  1893. return row[that.header.stateField];
  1894. });
  1895. };
  1896. BootstrapTable.prototype.getAllSelections = function () {
  1897. var that = this;
  1898. return $.grep(this.options.data, function (row) {
  1899. return row[that.header.stateField];
  1900. });
  1901. };
  1902. BootstrapTable.prototype.checkAll = function () {
  1903. this.checkAll_(true);
  1904. };
  1905. BootstrapTable.prototype.uncheckAll = function () {
  1906. this.checkAll_(false);
  1907. };
  1908. BootstrapTable.prototype.checkAll_ = function (checked) {
  1909. var rows;
  1910. if (!checked) {
  1911. rows = this.getSelections();
  1912. }
  1913. this.$selectItem.filter(':enabled').prop('checked', checked);
  1914. this.updateRows();
  1915. this.updateSelected();
  1916. if (checked) {
  1917. rows = this.getSelections();
  1918. }
  1919. this.trigger(checked ? 'check-all' : 'uncheck-all', rows);
  1920. };
  1921. BootstrapTable.prototype.check = function (index) {
  1922. this.check_(true, index);
  1923. };
  1924. BootstrapTable.prototype.uncheck = function (index) {
  1925. this.check_(false, index);
  1926. };
  1927. BootstrapTable.prototype.check_ = function (checked, index) {
  1928. this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  1929. this.data[index][this.header.stateField] = checked;
  1930. this.updateSelected();
  1931. this.trigger(checked ? 'check' : 'uncheck', this.data[index]);
  1932. };
  1933. BootstrapTable.prototype.checkBy = function (obj) {
  1934. this.checkBy_(true, obj);
  1935. };
  1936. BootstrapTable.prototype.uncheckBy = function (obj) {
  1937. this.checkBy_(false, obj);
  1938. };
  1939. BootstrapTable.prototype.checkBy_ = function (checked, obj) {
  1940. if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
  1941. return;
  1942. }
  1943. var that = this,
  1944. rows = [];
  1945. $.each(this.options.data, function (index, row) {
  1946. if (!row.hasOwnProperty(obj.field)) {
  1947. return false;
  1948. }
  1949. if ($.inArray(row[obj.field], obj.values) !== -1) {
  1950. that.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  1951. row[that.header.stateField] = checked;
  1952. rows.push(row);
  1953. that.trigger(checked ? 'check' : 'uncheck', row);
  1954. }
  1955. });
  1956. this.updateSelected();
  1957. this.trigger(checked ? 'check-some' : 'uncheck-some', rows);
  1958. };
  1959. BootstrapTable.prototype.destroy = function () {
  1960. this.$el.insertBefore(this.$container);
  1961. $(this.options.toolbar).insertBefore(this.$el);
  1962. this.$container.next().remove();
  1963. this.$container.remove();
  1964. this.$el.html(this.$el_.html())
  1965. .css('margin-top', '0')
  1966. .attr('class', this.$el_.attr('class') || ''); // reset the class
  1967. };
  1968. BootstrapTable.prototype.showLoading = function () {
  1969. this.$tableLoading.show();
  1970. };
  1971. BootstrapTable.prototype.hideLoading = function () {
  1972. this.$tableLoading.hide();
  1973. };
  1974. BootstrapTable.prototype.togglePagination = function () {
  1975. this.options.pagination = !this.options.pagination;
  1976. var button = this.$toolbar.find('button[name="paginationSwitch"] i');
  1977. if (this.options.pagination) {
  1978. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown);
  1979. } else {
  1980. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp);
  1981. }
  1982. this.updatePagination();
  1983. };
  1984. BootstrapTable.prototype.refresh = function (params) {
  1985. if (params && params.url) {
  1986. this.options.url = params.url;
  1987. this.options.pageNumber = 1;
  1988. }
  1989. this.initServer(params && params.silent, params && params.query);
  1990. };
  1991. BootstrapTable.prototype.resetWidth = function () {
  1992. if (this.options.showHeader && this.options.height) {
  1993. this.fitHeader();
  1994. }
  1995. if (this.options.showFooter) {
  1996. this.fitFooter();
  1997. }
  1998. };
  1999. BootstrapTable.prototype.showColumn = function (field) {
  2000. this.toggleColumn(getFieldIndex(this.columns, field), true, true);
  2001. };
  2002. BootstrapTable.prototype.hideColumn = function (field) {
  2003. this.toggleColumn(getFieldIndex(this.columns, field), false, true);
  2004. };
  2005. BootstrapTable.prototype.getHiddenColumns = function () {
  2006. return $.grep(this.columns, function( column ) {
  2007. return !column.visible;
  2008. });
  2009. };
  2010. BootstrapTable.prototype.filterBy = function (columns) {
  2011. this.filterColumns = $.isEmptyObject(columns) ? {} : columns;
  2012. this.options.pageNumber = 1;
  2013. this.initSearch();
  2014. this.updatePagination();
  2015. };
  2016. BootstrapTable.prototype.scrollTo = function (value) {
  2017. if (typeof value === 'string') {
  2018. value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0;
  2019. }
  2020. if (typeof value === 'number') {
  2021. this.$tableBody.scrollTop(value);
  2022. }
  2023. if (typeof value === 'undefined') {
  2024. return this.$tableBody.scrollTop();
  2025. }
  2026. };
  2027. BootstrapTable.prototype.getScrollPosition = function () {
  2028. return this.scrollTo();
  2029. };
  2030. BootstrapTable.prototype.selectPage = function (page) {
  2031. if (page > 0 && page <= this.options.totalPages) {
  2032. this.options.pageNumber = page;
  2033. this.updatePagination();
  2034. }
  2035. };
  2036. BootstrapTable.prototype.prevPage = function () {
  2037. if (this.options.pageNumber > 1) {
  2038. this.options.pageNumber--;
  2039. this.updatePagination();
  2040. }
  2041. };
  2042. BootstrapTable.prototype.nextPage = function () {
  2043. if (this.options.pageNumber < this.options.totalPages) {
  2044. this.options.pageNumber++;
  2045. this.updatePagination();
  2046. }
  2047. };
  2048. BootstrapTable.prototype.toggleView = function () {
  2049. this.options.cardView = !this.options.cardView;
  2050. this.initHeader();
  2051. // Fixed remove toolbar when click cardView button.
  2052. //that.initToolbar();
  2053. this.initBody();
  2054. this.trigger('toggle', this.options.cardView);
  2055. };
  2056. BootstrapTable.prototype.refreshOptions = function (options) {
  2057. //If the objects are equivalent then avoid the call of destroy / init methods
  2058. if (compareObjects(this.options, options, false)) {
  2059. return;
  2060. }
  2061. this.options = $.extend(this.options, options);
  2062. this.trigger('refresh-options', this.options);
  2063. this.destroy();
  2064. this.init();
  2065. };
  2066. BootstrapTable.prototype.resetSearch = function (text) {
  2067. var $search = this.$toolbar.find('.search input');
  2068. $search.val(text || '');
  2069. this.onSearch({currentTarget: $search});
  2070. };
  2071. // BOOTSTRAP TABLE PLUGIN DEFINITION
  2072. // =======================
  2073. var allowedMethods = [
  2074. 'getOptions',
  2075. 'getSelections', 'getAllSelections', 'getData',
  2076. 'load', 'append', 'prepend', 'remove', 'removeAll',
  2077. 'insertRow', 'updateRow', 'updateCell', 'removeByUniqueId',
  2078. 'getRowByUniqueId', 'showRow', 'hideRow', 'getRowsHidden',
  2079. 'mergeCells',
  2080. 'checkAll', 'uncheckAll',
  2081. 'check', 'uncheck',
  2082. 'checkBy', 'uncheckBy',
  2083. 'refresh',
  2084. 'resetView',
  2085. 'resetWidth',
  2086. 'destroy',
  2087. 'showLoading', 'hideLoading',
  2088. 'showColumn', 'hideColumn', 'getHiddenColumns',
  2089. 'filterBy',
  2090. 'scrollTo',
  2091. 'getScrollPosition',
  2092. 'selectPage', 'prevPage', 'nextPage',
  2093. 'togglePagination',
  2094. 'toggleView',
  2095. 'refreshOptions',
  2096. 'resetSearch'
  2097. ];
  2098. $.fn.bootstrapTable = function (option) {
  2099. var value,
  2100. args = Array.prototype.slice.call(arguments, 1);
  2101. this.each(function () {
  2102. var $this = $(this),
  2103. data = $this.data('bootstrap.table'),
  2104. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
  2105. typeof option === 'object' && option);
  2106. if (typeof option === 'string') {
  2107. if ($.inArray(option, allowedMethods) < 0) {
  2108. throw new Error("Unknown method: " + option);
  2109. }
  2110. if (!data) {
  2111. return;
  2112. }
  2113. value = data[option].apply(data, args);
  2114. if (option === 'destroy') {
  2115. $this.removeData('bootstrap.table');
  2116. }
  2117. }
  2118. if (!data) {
  2119. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  2120. }
  2121. });
  2122. return typeof value === 'undefined' ? this : value;
  2123. };
  2124. $.fn.bootstrapTable.Constructor = BootstrapTable;
  2125. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
  2126. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
  2127. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES;
  2128. $.fn.bootstrapTable.methods = allowedMethods;
  2129. // BOOTSTRAP TABLE INIT
  2130. // =======================
  2131. $(function () {
  2132. $('[data-toggle="table"]').bootstrapTable();
  2133. });
  2134. }(jQuery);