bootstrap-table.js 87 KB

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