bootstrap-table.js 80 KB

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