bootstrap-table.js 87 KB

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