bootstrap-table.js 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.10.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. .replace(/`/g, '&#x60;');
  160. }
  161. return text;
  162. };
  163. var getRealHeight = function ($el) {
  164. var height = 0;
  165. $el.children().each(function () {
  166. if (height < $(this).outerHeight(true)) {
  167. height = $(this).outerHeight(true);
  168. }
  169. });
  170. return height;
  171. };
  172. var getRealDataAttr = function (dataAttr) {
  173. for (var attr in dataAttr) {
  174. var auxAttr = attr.split(/(?=[A-Z])/).join('-').toLowerCase();
  175. if (auxAttr !== attr) {
  176. dataAttr[auxAttr] = dataAttr[attr];
  177. delete dataAttr[attr];
  178. }
  179. }
  180. return dataAttr;
  181. };
  182. var getItemField = function (item, field, escape) {
  183. var value = item;
  184. if (typeof field !== 'string' || item.hasOwnProperty(field)) {
  185. return escape ? escapeHTML(item[field]) : item[field];
  186. }
  187. var props = field.split('.');
  188. for (var p in props) {
  189. value = value && value[props[p]];
  190. }
  191. return escape ? escapeHTML(value) : value;
  192. };
  193. var isIEBrowser = function () {
  194. return !!(navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./));
  195. };
  196. var objectKeys = function () {
  197. // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
  198. if (!Object.keys) {
  199. Object.keys = (function() {
  200. var hasOwnProperty = Object.prototype.hasOwnProperty,
  201. hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
  202. dontEnums = [
  203. 'toString',
  204. 'toLocaleString',
  205. 'valueOf',
  206. 'hasOwnProperty',
  207. 'isPrototypeOf',
  208. 'propertyIsEnumerable',
  209. 'constructor'
  210. ],
  211. dontEnumsLength = dontEnums.length;
  212. return function(obj) {
  213. if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
  214. throw new TypeError('Object.keys called on non-object');
  215. }
  216. var result = [], prop, i;
  217. for (prop in obj) {
  218. if (hasOwnProperty.call(obj, prop)) {
  219. result.push(prop);
  220. }
  221. }
  222. if (hasDontEnumBug) {
  223. for (i = 0; i < dontEnumsLength; i++) {
  224. if (hasOwnProperty.call(obj, dontEnums[i])) {
  225. result.push(dontEnums[i]);
  226. }
  227. }
  228. }
  229. return result;
  230. };
  231. }());
  232. }
  233. };
  234. // BOOTSTRAP TABLE CLASS DEFINITION
  235. // ======================
  236. var BootstrapTable = function (el, options) {
  237. this.options = options;
  238. this.$el = $(el);
  239. this.$el_ = this.$el.clone();
  240. this.timeoutId_ = 0;
  241. this.timeoutFooter_ = 0;
  242. this.init();
  243. };
  244. BootstrapTable.DEFAULTS = {
  245. classes: 'table table-hover',
  246. locale: undefined,
  247. height: undefined,
  248. undefinedText: '-',
  249. sortName: undefined,
  250. sortOrder: 'asc',
  251. sortStable: false,
  252. striped: false,
  253. columns: [[]],
  254. data: [],
  255. dataField: 'rows',
  256. method: 'get',
  257. url: undefined,
  258. ajax: undefined,
  259. cache: true,
  260. contentType: 'application/json',
  261. dataType: 'json',
  262. ajaxOptions: {},
  263. queryParams: function (params) {
  264. return params;
  265. },
  266. queryParamsType: 'limit', // undefined
  267. responseHandler: function (res) {
  268. return res;
  269. },
  270. pagination: false,
  271. onlyInfoPagination: false,
  272. sidePagination: 'client', // client or server
  273. totalRows: 0, // server side need to set
  274. pageNumber: 1,
  275. pageSize: 10,
  276. pageList: [10, 25, 50, 100],
  277. paginationHAlign: 'right', //right, left
  278. paginationVAlign: 'bottom', //bottom, top, both
  279. paginationDetailHAlign: 'left', //right, left
  280. paginationPreText: '&lsaquo;',
  281. paginationNextText: '&rsaquo;',
  282. search: false,
  283. searchOnEnterKey: false,
  284. strictSearch: false,
  285. searchAlign: 'right',
  286. selectItemName: 'btSelectItem',
  287. showHeader: true,
  288. showFooter: false,
  289. showColumns: false,
  290. showPaginationSwitch: false,
  291. showRefresh: false,
  292. showToggle: false,
  293. buttonsAlign: 'right',
  294. smartDisplay: true,
  295. escape: false,
  296. minimumCountColumns: 1,
  297. idField: undefined,
  298. uniqueId: undefined,
  299. cardView: false,
  300. detailView: false,
  301. detailFormatter: function (index, row) {
  302. return '';
  303. },
  304. trimOnSearch: true,
  305. clickToSelect: false,
  306. singleSelect: false,
  307. toolbar: undefined,
  308. toolbarAlign: 'left',
  309. checkboxHeader: true,
  310. sortable: true,
  311. silentSort: true,
  312. maintainSelected: false,
  313. searchTimeOut: 500,
  314. searchText: '',
  315. iconSize: undefined,
  316. buttonsClass: 'default',
  317. iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome)
  318. icons: {
  319. paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
  320. paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
  321. refresh: 'glyphicon-refresh icon-refresh',
  322. toggle: 'glyphicon-list-alt icon-list-alt',
  323. columns: 'glyphicon-th icon-th',
  324. detailOpen: 'glyphicon-plus icon-plus',
  325. detailClose: 'glyphicon-minus icon-minus'
  326. },
  327. customSearch: $.noop,
  328. customSort: $.noop,
  329. rowStyle: function (row, index) {
  330. return {};
  331. },
  332. rowAttributes: function (row, index) {
  333. return {};
  334. },
  335. footerStyle: function (row, index) {
  336. return {};
  337. },
  338. onAll: function (name, args) {
  339. return false;
  340. },
  341. onClickCell: function (field, value, row, $element) {
  342. return false;
  343. },
  344. onDblClickCell: function (field, value, row, $element) {
  345. return false;
  346. },
  347. onClickRow: function (item, $element) {
  348. return false;
  349. },
  350. onDblClickRow: function (item, $element) {
  351. return false;
  352. },
  353. onSort: function (name, order) {
  354. return false;
  355. },
  356. onCheck: function (row) {
  357. return false;
  358. },
  359. onUncheck: function (row) {
  360. return false;
  361. },
  362. onCheckAll: function (rows) {
  363. return false;
  364. },
  365. onUncheckAll: function (rows) {
  366. return false;
  367. },
  368. onCheckSome: function (rows) {
  369. return false;
  370. },
  371. onUncheckSome: function (rows) {
  372. return false;
  373. },
  374. onLoadSuccess: function (data) {
  375. return false;
  376. },
  377. onLoadError: function (status) {
  378. return false;
  379. },
  380. onColumnSwitch: function (field, checked) {
  381. return false;
  382. },
  383. onPageChange: function (number, size) {
  384. return false;
  385. },
  386. onSearch: function (text) {
  387. return false;
  388. },
  389. onToggle: function (cardView) {
  390. return false;
  391. },
  392. onPreBody: function (data) {
  393. return false;
  394. },
  395. onPostBody: function () {
  396. return false;
  397. },
  398. onPostHeader: function () {
  399. return false;
  400. },
  401. onExpandRow: function (index, row, $detail) {
  402. return false;
  403. },
  404. onCollapseRow: function (index, row) {
  405. return false;
  406. },
  407. onRefreshOptions: function (options) {
  408. return false;
  409. },
  410. onRefresh: function (params) {
  411. return false;
  412. },
  413. onResetView: function () {
  414. return false;
  415. }
  416. };
  417. BootstrapTable.LOCALES = [];
  418. BootstrapTable.LOCALES['en-US'] = BootstrapTable.LOCALES.en = {
  419. formatLoadingMessage: function () {
  420. return 'Loading, please wait...';
  421. },
  422. formatRecordsPerPage: function (pageNumber) {
  423. return sprintf('%s rows per page', pageNumber);
  424. },
  425. formatShowingRows: function (pageFrom, pageTo, totalRows) {
  426. return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows);
  427. },
  428. formatDetailPagination: function (totalRows) {
  429. return sprintf('Showing %s rows', totalRows);
  430. },
  431. formatSearch: function () {
  432. return 'Search';
  433. },
  434. formatNoMatches: function () {
  435. return 'No matching records found';
  436. },
  437. formatPaginationSwitch: function () {
  438. return 'Hide/Show pagination';
  439. },
  440. formatRefresh: function () {
  441. return 'Refresh';
  442. },
  443. formatToggle: function () {
  444. return 'Toggle';
  445. },
  446. formatColumns: function () {
  447. return 'Columns';
  448. },
  449. formatAllRows: function () {
  450. return 'All';
  451. }
  452. };
  453. $.extend(BootstrapTable.DEFAULTS, BootstrapTable.LOCALES['en-US']);
  454. BootstrapTable.COLUMN_DEFAULTS = {
  455. radio: false,
  456. checkbox: false,
  457. checkboxEnabled: true,
  458. field: undefined,
  459. title: undefined,
  460. titleTooltip: undefined,
  461. 'class': undefined,
  462. align: undefined, // left, right, center
  463. halign: undefined, // left, right, center
  464. falign: undefined, // left, right, center
  465. valign: undefined, // top, middle, bottom
  466. width: undefined,
  467. sortable: false,
  468. order: 'asc', // asc, desc
  469. visible: true,
  470. switchable: true,
  471. clickToSelect: true,
  472. formatter: undefined,
  473. footerFormatter: undefined,
  474. events: undefined,
  475. sorter: undefined,
  476. sortName: undefined,
  477. cellStyle: undefined,
  478. searchable: true,
  479. searchFormatter: true,
  480. cardVisible: true
  481. };
  482. BootstrapTable.EVENTS = {
  483. 'all.bs.table': 'onAll',
  484. 'click-cell.bs.table': 'onClickCell',
  485. 'dbl-click-cell.bs.table': 'onDblClickCell',
  486. 'click-row.bs.table': 'onClickRow',
  487. 'dbl-click-row.bs.table': 'onDblClickRow',
  488. 'sort.bs.table': 'onSort',
  489. 'check.bs.table': 'onCheck',
  490. 'uncheck.bs.table': 'onUncheck',
  491. 'check-all.bs.table': 'onCheckAll',
  492. 'uncheck-all.bs.table': 'onUncheckAll',
  493. 'check-some.bs.table': 'onCheckSome',
  494. 'uncheck-some.bs.table': 'onUncheckSome',
  495. 'load-success.bs.table': 'onLoadSuccess',
  496. 'load-error.bs.table': 'onLoadError',
  497. 'column-switch.bs.table': 'onColumnSwitch',
  498. 'page-change.bs.table': 'onPageChange',
  499. 'search.bs.table': 'onSearch',
  500. 'toggle.bs.table': 'onToggle',
  501. 'pre-body.bs.table': 'onPreBody',
  502. 'post-body.bs.table': 'onPostBody',
  503. 'post-header.bs.table': 'onPostHeader',
  504. 'expand-row.bs.table': 'onExpandRow',
  505. 'collapse-row.bs.table': 'onCollapseRow',
  506. 'refresh-options.bs.table': 'onRefreshOptions',
  507. 'reset-view.bs.table': 'onResetView',
  508. 'refresh.bs.table': 'onRefresh'
  509. };
  510. BootstrapTable.prototype.init = function () {
  511. this.initLocale();
  512. this.initContainer();
  513. this.initTable();
  514. this.initHeader();
  515. this.initData();
  516. this.initFooter();
  517. this.initToolbar();
  518. this.initPagination();
  519. this.initBody();
  520. this.initSearchText();
  521. this.initServer();
  522. };
  523. BootstrapTable.prototype.initLocale = function () {
  524. if (this.options.locale) {
  525. var parts = this.options.locale.split(/-|_/);
  526. parts[0].toLowerCase();
  527. if (parts[1]) parts[1].toUpperCase();
  528. if ($.fn.bootstrapTable.locales[this.options.locale]) {
  529. // locale as requested
  530. $.extend(this.options, $.fn.bootstrapTable.locales[this.options.locale]);
  531. } else if ($.fn.bootstrapTable.locales[parts.join('-')]) {
  532. // locale with sep set to - (in case original was specified with _)
  533. $.extend(this.options, $.fn.bootstrapTable.locales[parts.join('-')]);
  534. } else if ($.fn.bootstrapTable.locales[parts[0]]) {
  535. // short locale language code (i.e. 'en')
  536. $.extend(this.options, $.fn.bootstrapTable.locales[parts[0]]);
  537. }
  538. }
  539. };
  540. BootstrapTable.prototype.initContainer = function () {
  541. this.$container = $([
  542. '<div class="bootstrap-table">',
  543. '<div class="fixed-table-toolbar"></div>',
  544. this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
  545. '<div class="fixed-table-pagination" style="clear: both;"></div>' :
  546. '',
  547. '<div class="fixed-table-container">',
  548. '<div class="fixed-table-header"><table></table></div>',
  549. '<div class="fixed-table-body">',
  550. '<div class="fixed-table-loading">',
  551. this.options.formatLoadingMessage(),
  552. '</div>',
  553. '</div>',
  554. '<div class="fixed-table-footer"><table><tr></tr></table></div>',
  555. this.options.paginationVAlign === 'bottom' || this.options.paginationVAlign === 'both' ?
  556. '<div class="fixed-table-pagination"></div>' :
  557. '',
  558. '</div>',
  559. '</div>'
  560. ].join(''));
  561. this.$container.insertAfter(this.$el);
  562. this.$tableContainer = this.$container.find('.fixed-table-container');
  563. this.$tableHeader = this.$container.find('.fixed-table-header');
  564. this.$tableBody = this.$container.find('.fixed-table-body');
  565. this.$tableLoading = this.$container.find('.fixed-table-loading');
  566. this.$tableFooter = this.$container.find('.fixed-table-footer');
  567. this.$toolbar = this.$container.find('.fixed-table-toolbar');
  568. this.$pagination = this.$container.find('.fixed-table-pagination');
  569. this.$tableBody.append(this.$el);
  570. this.$container.after('<div class="clearfix"></div>');
  571. this.$el.addClass(this.options.classes);
  572. if (this.options.striped) {
  573. this.$el.addClass('table-striped');
  574. }
  575. if ($.inArray('table-no-bordered', this.options.classes.split(' ')) !== -1) {
  576. this.$tableContainer.addClass('table-no-bordered');
  577. }
  578. };
  579. BootstrapTable.prototype.initTable = function () {
  580. var that = this,
  581. columns = [],
  582. data = [];
  583. this.$header = this.$el.find('>thead');
  584. if (!this.$header.length) {
  585. this.$header = $('<thead></thead>').appendTo(this.$el);
  586. }
  587. this.$header.find('tr').each(function () {
  588. var column = [];
  589. $(this).find('th').each(function () {
  590. // Fix #2014 - getFieldIndex and elsewhere assume this is string, causes issues if not
  591. if (typeof $(this).data('field') !== 'undefined') {
  592. $(this).data('field', $(this).data('field') + '');
  593. }
  594. column.push($.extend({}, {
  595. title: $(this).html(),
  596. 'class': $(this).attr('class'),
  597. titleTooltip: $(this).attr('title'),
  598. rowspan: $(this).attr('rowspan') ? +$(this).attr('rowspan') : undefined,
  599. colspan: $(this).attr('colspan') ? +$(this).attr('colspan') : undefined
  600. }, $(this).data()));
  601. });
  602. columns.push(column);
  603. });
  604. if (!$.isArray(this.options.columns[0])) {
  605. this.options.columns = [this.options.columns];
  606. }
  607. this.options.columns = $.extend(true, [], columns, this.options.columns);
  608. this.columns = [];
  609. setFieldIndex(this.options.columns);
  610. $.each(this.options.columns, function (i, columns) {
  611. $.each(columns, function (j, column) {
  612. column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column);
  613. if (typeof column.fieldIndex !== 'undefined') {
  614. that.columns[column.fieldIndex] = column;
  615. }
  616. that.options.columns[i][j] = column;
  617. });
  618. });
  619. // if options.data is setting, do not process tbody data
  620. if (this.options.data.length) {
  621. return;
  622. }
  623. var m = [];
  624. this.$el.find('>tbody>tr').each(function (y) {
  625. var row = {};
  626. // save tr's id, class and data-* attributes
  627. row._id = $(this).attr('id');
  628. row._class = $(this).attr('class');
  629. row._data = getRealDataAttr($(this).data());
  630. $(this).find('>td').each(function (x) {
  631. var $this = $(this),
  632. cspan = +$this.attr('colspan') || 1,
  633. rspan = +$this.attr('rowspan') || 1,
  634. tx, ty;
  635. for (; m[y] && m[y][x]; x++); //skip already occupied cells in current row
  636. for (tx = x; tx < x + cspan; tx++) { //mark matrix elements occupied by current cell with true
  637. for (ty = y; ty < y + rspan; ty++) {
  638. if (!m[ty]) { //fill missing rows
  639. m[ty] = [];
  640. }
  641. m[ty][tx] = true;
  642. }
  643. }
  644. var field = that.columns[x].field;
  645. row[field] = $(this).html();
  646. // save td's id, class and data-* attributes
  647. row['_' + field + '_id'] = $(this).attr('id');
  648. row['_' + field + '_class'] = $(this).attr('class');
  649. row['_' + field + '_rowspan'] = $(this).attr('rowspan');
  650. row['_' + field + '_colspan'] = $(this).attr('colspan');
  651. row['_' + field + '_title'] = $(this).attr('title');
  652. row['_' + field + '_data'] = getRealDataAttr($(this).data());
  653. });
  654. data.push(row);
  655. });
  656. this.options.data = data;
  657. if (data.length) this.fromHtml = true;
  658. };
  659. BootstrapTable.prototype.initHeader = function () {
  660. var that = this,
  661. visibleColumns = {},
  662. html = [];
  663. this.header = {
  664. fields: [],
  665. styles: [],
  666. classes: [],
  667. formatters: [],
  668. events: [],
  669. sorters: [],
  670. sortNames: [],
  671. cellStyles: [],
  672. searchables: []
  673. };
  674. $.each(this.options.columns, function (i, columns) {
  675. html.push('<tr>');
  676. if (i === 0 && !that.options.cardView && that.options.detailView) {
  677. html.push(sprintf('<th class="detail" rowspan="%s"><div class="fht-cell"></div></th>',
  678. that.options.columns.length));
  679. }
  680. $.each(columns, function (j, column) {
  681. var text = '',
  682. halign = '', // header align style
  683. align = '', // body align style
  684. style = '',
  685. class_ = sprintf(' class="%s"', column['class']),
  686. order = that.options.sortOrder || column.order,
  687. unitWidth = 'px',
  688. width = column.width;
  689. if (column.width !== undefined && (!that.options.cardView)) {
  690. if (typeof column.width === 'string') {
  691. if (column.width.indexOf('%') !== -1) {
  692. unitWidth = '%';
  693. }
  694. }
  695. }
  696. if (column.width && typeof column.width === 'string') {
  697. width = column.width.replace('%', '').replace('px', '');
  698. }
  699. halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align);
  700. align = sprintf('text-align: %s; ', column.align);
  701. style = sprintf('vertical-align: %s; ', column.valign);
  702. style += sprintf('width: %s; ', (column.checkbox || column.radio) && !width ?
  703. '36px' : (width ? width + unitWidth : undefined));
  704. if (typeof column.fieldIndex !== 'undefined') {
  705. that.header.fields[column.fieldIndex] = column.field;
  706. that.header.styles[column.fieldIndex] = align + style;
  707. that.header.classes[column.fieldIndex] = class_;
  708. that.header.formatters[column.fieldIndex] = column.formatter;
  709. that.header.events[column.fieldIndex] = column.events;
  710. that.header.sorters[column.fieldIndex] = column.sorter;
  711. that.header.sortNames[column.fieldIndex] = column.sortName;
  712. that.header.cellStyles[column.fieldIndex] = column.cellStyle;
  713. that.header.searchables[column.fieldIndex] = column.searchable;
  714. if (!column.visible) {
  715. return;
  716. }
  717. if (that.options.cardView && (!column.cardVisible)) {
  718. return;
  719. }
  720. visibleColumns[column.field] = column;
  721. }
  722. html.push('<th' + sprintf(' title="%s"', column.titleTooltip),
  723. column.checkbox || column.radio ?
  724. sprintf(' class="bs-checkbox %s"', column['class'] || '') :
  725. class_,
  726. sprintf(' style="%s"', halign + style),
  727. sprintf(' rowspan="%s"', column.rowspan),
  728. sprintf(' colspan="%s"', column.colspan),
  729. sprintf(' data-field="%s"', column.field),
  730. "tabindex='0'",
  731. '>');
  732. html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ?
  733. 'sortable both' : ''));
  734. text = column.title;
  735. if (column.checkbox) {
  736. if (!that.options.singleSelect && that.options.checkboxHeader) {
  737. text = '<input name="btSelectAll" type="checkbox" />';
  738. }
  739. that.header.stateField = column.field;
  740. }
  741. if (column.radio) {
  742. text = '';
  743. that.header.stateField = column.field;
  744. that.options.singleSelect = true;
  745. }
  746. html.push(text);
  747. html.push('</div>');
  748. html.push('<div class="fht-cell"></div>');
  749. html.push('</div>');
  750. html.push('</th>');
  751. });
  752. html.push('</tr>');
  753. });
  754. this.$header.html(html.join(''));
  755. this.$header.find('th[data-field]').each(function (i) {
  756. $(this).data(visibleColumns[$(this).data('field')]);
  757. });
  758. this.$container.off('click', '.th-inner').on('click', '.th-inner', function (event) {
  759. var target = $(this);
  760. if (that.options.detailView) {
  761. if (target.closest('.bootstrap-table')[0] !== that.$container[0])
  762. return false;
  763. }
  764. if (that.options.sortable && target.parent().data().sortable) {
  765. that.onSort(event);
  766. }
  767. });
  768. this.$header.children().children().off('keypress').on('keypress', function (event) {
  769. if (that.options.sortable && $(this).data().sortable) {
  770. var code = event.keyCode || event.which;
  771. if (code == 13) { //Enter keycode
  772. that.onSort(event);
  773. }
  774. }
  775. });
  776. $(window).off('resize.bootstrap-table');
  777. if (!this.options.showHeader || this.options.cardView) {
  778. this.$header.hide();
  779. this.$tableHeader.hide();
  780. this.$tableLoading.css('top', 0);
  781. } else {
  782. this.$header.show();
  783. this.$tableHeader.show();
  784. this.$tableLoading.css('top', this.$header.outerHeight() + 1);
  785. // Assign the correct sortable arrow
  786. this.getCaret();
  787. $(window).on('resize.bootstrap-table', $.proxy(this.resetWidth, this));
  788. }
  789. this.$selectAll = this.$header.find('[name="btSelectAll"]');
  790. this.$selectAll.off('click').on('click', function () {
  791. var checked = $(this).prop('checked');
  792. that[checked ? 'checkAll' : 'uncheckAll']();
  793. that.updateSelected();
  794. });
  795. };
  796. BootstrapTable.prototype.initFooter = function () {
  797. if (!this.options.showFooter || this.options.cardView) {
  798. this.$tableFooter.hide();
  799. } else {
  800. this.$tableFooter.show();
  801. }
  802. };
  803. /**
  804. * @param data
  805. * @param type: append / prepend
  806. */
  807. BootstrapTable.prototype.initData = function (data, type) {
  808. if (type === 'append') {
  809. this.data = this.data.concat(data);
  810. } else if (type === 'prepend') {
  811. this.data = [].concat(data).concat(this.data);
  812. } else {
  813. this.data = data || this.options.data;
  814. }
  815. // Fix #839 Records deleted when adding new row on filtered table
  816. if (type === 'append') {
  817. this.options.data = this.options.data.concat(data);
  818. } else if (type === 'prepend') {
  819. this.options.data = [].concat(data).concat(this.options.data);
  820. } else {
  821. this.options.data = this.data;
  822. }
  823. if (this.options.sidePagination === 'server') {
  824. return;
  825. }
  826. this.initSort();
  827. };
  828. BootstrapTable.prototype.initSort = function () {
  829. var that = this,
  830. name = this.options.sortName,
  831. order = this.options.sortOrder === 'desc' ? -1 : 1,
  832. index = $.inArray(this.options.sortName, this.header.fields);
  833. if (this.options.customSort !== $.noop) {
  834. this.options.customSort.apply(this, [this.options.sortName, this.options.sortOrder]);
  835. return;
  836. }
  837. if (index !== -1) {
  838. if (this.options.sortStable) {
  839. $.each(this.data, function (i, row) {
  840. if (!row.hasOwnProperty('_position')) row._position = i;
  841. });
  842. }
  843. this.data.sort(function (a, b) {
  844. if (that.header.sortNames[index]) {
  845. name = that.header.sortNames[index];
  846. }
  847. var aa = getItemField(a, name, that.options.escape),
  848. bb = getItemField(b, name, that.options.escape),
  849. value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]);
  850. if (value !== undefined) {
  851. return order * value;
  852. }
  853. // Fix #161: undefined or null string sort bug.
  854. if (aa === undefined || aa === null) {
  855. aa = '';
  856. }
  857. if (bb === undefined || bb === null) {
  858. bb = '';
  859. }
  860. if (that.options.sortStable && aa === bb) {
  861. aa = a._position;
  862. bb = b._position;
  863. }
  864. // IF both values are numeric, do a numeric comparison
  865. if ($.isNumeric(aa) && $.isNumeric(bb)) {
  866. // Convert numerical values form string to float.
  867. aa = parseFloat(aa);
  868. bb = parseFloat(bb);
  869. if (aa < bb) {
  870. return order * -1;
  871. }
  872. return order;
  873. }
  874. if (aa === bb) {
  875. return 0;
  876. }
  877. // If value is not a string, convert to string
  878. if (typeof aa !== 'string') {
  879. aa = aa.toString();
  880. }
  881. if (aa.localeCompare(bb) === -1) {
  882. return order * -1;
  883. }
  884. return order;
  885. });
  886. }
  887. };
  888. BootstrapTable.prototype.onSort = function (event) {
  889. var $this = event.type === "keypress" ? $(event.currentTarget) : $(event.currentTarget).parent(),
  890. $this_ = this.$header.find('th').eq($this.index());
  891. this.$header.add(this.$header_).find('span.order').remove();
  892. if (this.options.sortName === $this.data('field')) {
  893. this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc';
  894. } else {
  895. this.options.sortName = $this.data('field');
  896. this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
  897. }
  898. this.trigger('sort', this.options.sortName, this.options.sortOrder);
  899. $this.add($this_).data('order', this.options.sortOrder);
  900. // Assign the correct sortable arrow
  901. this.getCaret();
  902. if (this.options.sidePagination === 'server') {
  903. this.initServer(this.options.silentSort);
  904. return;
  905. }
  906. this.initSort();
  907. this.initBody();
  908. };
  909. BootstrapTable.prototype.initToolbar = function () {
  910. var that = this,
  911. html = [],
  912. timeoutId = 0,
  913. $keepOpen,
  914. $search,
  915. switchableCount = 0;
  916. if (this.$toolbar.find('.bs-bars').children().length) {
  917. $('body').append($(this.options.toolbar));
  918. }
  919. this.$toolbar.html('');
  920. if (typeof this.options.toolbar === 'string' || typeof this.options.toolbar === 'object') {
  921. $(sprintf('<div class="bs-bars pull-%s"></div>', this.options.toolbarAlign))
  922. .appendTo(this.$toolbar)
  923. .append($(this.options.toolbar));
  924. }
  925. // showColumns, showToggle, showRefresh
  926. html = [sprintf('<div class="columns columns-%s btn-group pull-%s">',
  927. this.options.buttonsAlign, this.options.buttonsAlign)];
  928. if (typeof this.options.icons === 'string') {
  929. this.options.icons = calculateObjectValue(null, this.options.icons);
  930. }
  931. if (this.options.showPaginationSwitch) {
  932. html.push(sprintf('<button class="btn' +
  933. sprintf(' btn-%s', this.options.buttonsClass) +
  934. '" type="button" name="paginationSwitch" title="%s">',
  935. this.options.formatPaginationSwitch()),
  936. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown),
  937. '</button>');
  938. }
  939. if (this.options.showRefresh) {
  940. html.push(sprintf('<button class="btn' +
  941. sprintf(' btn-%s', this.options.buttonsClass) +
  942. sprintf(' btn-%s', this.options.iconSize) +
  943. '" type="button" name="refresh" title="%s">',
  944. this.options.formatRefresh()),
  945. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh),
  946. '</button>');
  947. }
  948. if (this.options.showToggle) {
  949. html.push(sprintf('<button class="btn' +
  950. sprintf(' btn-%s', this.options.buttonsClass) +
  951. sprintf(' btn-%s', this.options.iconSize) +
  952. '" type="button" name="toggle" title="%s">',
  953. this.options.formatToggle()),
  954. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggle),
  955. '</button>');
  956. }
  957. if (this.options.showColumns) {
  958. html.push(sprintf('<div class="keep-open btn-group" title="%s">',
  959. this.options.formatColumns()),
  960. '<button type="button" class="btn' +
  961. sprintf(' btn-%s', this.options.buttonsClass) +
  962. sprintf(' btn-%s', this.options.iconSize) +
  963. ' dropdown-toggle" data-toggle="dropdown">',
  964. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns),
  965. ' <span class="caret"></span>',
  966. '</button>',
  967. '<ul class="dropdown-menu" role="menu">');
  968. $.each(this.columns, function (i, column) {
  969. if (column.radio || column.checkbox) {
  970. return;
  971. }
  972. if (that.options.cardView && (!column.cardVisible)) {
  973. return;
  974. }
  975. var checked = column.visible ? ' checked="checked"' : '';
  976. if (column.switchable) {
  977. html.push(sprintf('<li>' +
  978. '<label><input type="checkbox" data-field="%s" value="%s"%s> %s</label>' +
  979. '</li>', column.field, i, checked, column.title));
  980. switchableCount++;
  981. }
  982. });
  983. html.push('</ul>',
  984. '</div>');
  985. }
  986. html.push('</div>');
  987. // Fix #188: this.showToolbar is for extensions
  988. if (this.showToolbar || html.length > 2) {
  989. this.$toolbar.append(html.join(''));
  990. }
  991. if (this.options.showPaginationSwitch) {
  992. this.$toolbar.find('button[name="paginationSwitch"]')
  993. .off('click').on('click', $.proxy(this.togglePagination, this));
  994. }
  995. if (this.options.showRefresh) {
  996. this.$toolbar.find('button[name="refresh"]')
  997. .off('click').on('click', $.proxy(this.refresh, this));
  998. }
  999. if (this.options.showToggle) {
  1000. this.$toolbar.find('button[name="toggle"]')
  1001. .off('click').on('click', function () {
  1002. that.toggleView();
  1003. });
  1004. }
  1005. if (this.options.showColumns) {
  1006. $keepOpen = this.$toolbar.find('.keep-open');
  1007. if (switchableCount <= this.options.minimumCountColumns) {
  1008. $keepOpen.find('input').prop('disabled', true);
  1009. }
  1010. $keepOpen.find('li').off('click').on('click', function (event) {
  1011. event.stopImmediatePropagation();
  1012. });
  1013. $keepOpen.find('input').off('click').on('click', function () {
  1014. var $this = $(this);
  1015. that.toggleColumn($(this).val(), $this.prop('checked'), false);
  1016. that.trigger('column-switch', $(this).data('field'), $this.prop('checked'));
  1017. });
  1018. }
  1019. if (this.options.search) {
  1020. html = [];
  1021. html.push(
  1022. '<div class="pull-' + this.options.searchAlign + ' search">',
  1023. sprintf('<input class="form-control' +
  1024. sprintf(' input-%s', this.options.iconSize) +
  1025. '" type="text" placeholder="%s">',
  1026. this.options.formatSearch()),
  1027. '</div>');
  1028. this.$toolbar.append(html.join(''));
  1029. $search = this.$toolbar.find('.search input');
  1030. $search.off('keyup drop').on('keyup drop', function (event) {
  1031. if (that.options.searchOnEnterKey) {
  1032. if (event.keyCode !== 13) {
  1033. return;
  1034. }
  1035. }
  1036. if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
  1037. return;
  1038. }
  1039. clearTimeout(timeoutId); // doesn't matter if it's 0
  1040. timeoutId = setTimeout(function () {
  1041. that.onSearch(event);
  1042. }, that.options.searchTimeOut);
  1043. });
  1044. if (isIEBrowser()) {
  1045. $search.off('mouseup').on('mouseup', function (event) {
  1046. clearTimeout(timeoutId); // doesn't matter if it's 0
  1047. timeoutId = setTimeout(function () {
  1048. that.onSearch(event);
  1049. }, that.options.searchTimeOut);
  1050. });
  1051. }
  1052. }
  1053. };
  1054. BootstrapTable.prototype.onSearch = function (event) {
  1055. var text = $.trim($(event.currentTarget).val());
  1056. // trim search input
  1057. if (this.options.trimOnSearch && $(event.currentTarget).val() !== text) {
  1058. $(event.currentTarget).val(text);
  1059. }
  1060. if (text === this.searchText) {
  1061. return;
  1062. }
  1063. this.searchText = text;
  1064. this.options.searchText = text;
  1065. this.options.pageNumber = 1;
  1066. this.initSearch();
  1067. this.updatePagination();
  1068. this.trigger('search', text);
  1069. };
  1070. BootstrapTable.prototype.initSearch = function () {
  1071. var that = this;
  1072. if (this.options.sidePagination !== 'server') {
  1073. if (this.options.customSearch !== $.noop) {
  1074. this.options.customSearch.apply(this, [this.searchText]);
  1075. return;
  1076. }
  1077. var s = !this.options.escape ? this.searchText && escapeHTML(this.searchText).toLowerCase()
  1078. : this.searchText && this.searchText.toLowerCase();
  1079. var f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns;
  1080. // Check filter
  1081. this.data = f ? $.grep(this.options.data, function (item, i) {
  1082. for (var key in f) {
  1083. if ($.isArray(f[key])) {
  1084. if ($.inArray(item[key], f[key]) === -1) {
  1085. return false;
  1086. }
  1087. } else if (item[key] !== f[key]) {
  1088. return false;
  1089. }
  1090. }
  1091. return true;
  1092. }) : this.options.data;
  1093. this.data = s ? $.grep(this.data, function (item, i) {
  1094. for (var key in item) {
  1095. key = $.isNumeric(key) ? parseInt(key, 10) : key;
  1096. var value = item[key],
  1097. column = that.columns[getFieldIndex(that.columns, key)],
  1098. j = $.inArray(key, that.header.fields);
  1099. // Fix #142: search use formatted data
  1100. if (column && column.searchFormatter) {
  1101. value = calculateObjectValue(column,
  1102. that.header.formatters[j], [value, item, i], value);
  1103. }
  1104. var index = $.inArray(key, that.header.fields);
  1105. if (index !== -1 && that.header.searchables[index] && (typeof value === 'string' || typeof value === 'number')) {
  1106. if (that.options.strictSearch) {
  1107. if ((value + '').toLowerCase() === s) {
  1108. return true;
  1109. }
  1110. } else {
  1111. if ((value + '').toLowerCase().indexOf(s) !== -1) {
  1112. return true;
  1113. }
  1114. }
  1115. }
  1116. }
  1117. return false;
  1118. }) : this.data;
  1119. }
  1120. };
  1121. BootstrapTable.prototype.initPagination = function () {
  1122. if (!this.options.pagination) {
  1123. this.$pagination.hide();
  1124. return;
  1125. } else {
  1126. this.$pagination.show();
  1127. }
  1128. var that = this,
  1129. html = [],
  1130. $allSelected = false,
  1131. i, from, to,
  1132. $pageList,
  1133. $first, $pre,
  1134. $next, $last,
  1135. $number,
  1136. data = this.getData(),
  1137. pageList = this.options.pageList;
  1138. if (this.options.sidePagination !== 'server') {
  1139. this.options.totalRows = data.length;
  1140. }
  1141. this.totalPages = 0;
  1142. if (this.options.totalRows) {
  1143. if (this.options.pageSize === this.options.formatAllRows()) {
  1144. this.options.pageSize = this.options.totalRows;
  1145. $allSelected = true;
  1146. } else if (this.options.pageSize === this.options.totalRows) {
  1147. // Fix #667 Table with pagination,
  1148. // multiple pages and a search that matches to one page throws exception
  1149. var pageLst = typeof this.options.pageList === 'string' ?
  1150. this.options.pageList.replace('[', '').replace(']', '')
  1151. .replace(/ /g, '').toLowerCase().split(',') : this.options.pageList;
  1152. if ($.inArray(this.options.formatAllRows().toLowerCase(), pageLst) > -1) {
  1153. $allSelected = true;
  1154. }
  1155. }
  1156. this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
  1157. this.options.totalPages = this.totalPages;
  1158. }
  1159. if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
  1160. this.options.pageNumber = this.totalPages;
  1161. }
  1162. this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
  1163. this.pageTo = this.options.pageNumber * this.options.pageSize;
  1164. if (this.pageTo > this.options.totalRows) {
  1165. this.pageTo = this.options.totalRows;
  1166. }
  1167. html.push(
  1168. '<div class="pull-' + this.options.paginationDetailHAlign + ' pagination-detail">',
  1169. '<span class="pagination-info">',
  1170. this.options.onlyInfoPagination ? this.options.formatDetailPagination(this.options.totalRows) :
  1171. this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
  1172. '</span>');
  1173. if (!this.options.onlyInfoPagination) {
  1174. html.push('<span class="page-list">');
  1175. var pageNumber = [
  1176. sprintf('<span class="btn-group %s">',
  1177. this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
  1178. 'dropdown' : 'dropup'),
  1179. '<button type="button" class="btn' +
  1180. sprintf(' btn-%s', this.options.buttonsClass) +
  1181. sprintf(' btn-%s', this.options.iconSize) +
  1182. ' dropdown-toggle" data-toggle="dropdown">',
  1183. '<span class="page-size">',
  1184. $allSelected ? this.options.formatAllRows() : this.options.pageSize,
  1185. '</span>',
  1186. ' <span class="caret"></span>',
  1187. '</button>',
  1188. '<ul class="dropdown-menu" role="menu">'
  1189. ];
  1190. if (typeof this.options.pageList === 'string') {
  1191. var list = this.options.pageList.replace('[', '').replace(']', '')
  1192. .replace(/ /g, '').split(',');
  1193. pageList = [];
  1194. $.each(list, function (i, value) {
  1195. pageList.push(value.toUpperCase() === that.options.formatAllRows().toUpperCase() ?
  1196. that.options.formatAllRows() : +value);
  1197. });
  1198. }
  1199. $.each(pageList, function (i, page) {
  1200. if (!that.options.smartDisplay || i === 0 || pageList[i - 1] <= that.options.totalRows) {
  1201. var active;
  1202. if ($allSelected) {
  1203. active = page === that.options.formatAllRows() ? ' class="active"' : '';
  1204. } else {
  1205. active = page === that.options.pageSize ? ' class="active"' : '';
  1206. }
  1207. pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page));
  1208. }
  1209. });
  1210. pageNumber.push('</ul></span>');
  1211. html.push(this.options.formatRecordsPerPage(pageNumber.join('')));
  1212. html.push('</span>');
  1213. html.push('</div>',
  1214. '<div class="pull-' + this.options.paginationHAlign + ' pagination">',
  1215. '<ul class="pagination' + sprintf(' pagination-%s', this.options.iconSize) + '">',
  1216. '<li class="page-pre"><a href="javascript:void(0)">' + this.options.paginationPreText + '</a></li>');
  1217. if (this.totalPages < 5) {
  1218. from = 1;
  1219. to = this.totalPages;
  1220. } else {
  1221. from = this.options.pageNumber - 2;
  1222. to = from + 4;
  1223. if (from < 1) {
  1224. from = 1;
  1225. to = 5;
  1226. }
  1227. if (to > this.totalPages) {
  1228. to = this.totalPages;
  1229. from = to - 4;
  1230. }
  1231. }
  1232. if (this.totalPages >= 6) {
  1233. if (this.options.pageNumber >= 3) {
  1234. html.push('<li class="page-first' + (1 === this.options.pageNumber ? ' active' : '') + '">',
  1235. '<a href="javascript:void(0)">', 1, '</a>',
  1236. '</li>');
  1237. from++;
  1238. }
  1239. if (this.options.pageNumber >= 4) {
  1240. if (this.options.pageNumber == 4 || this.totalPages == 6 || this.totalPages == 7) {
  1241. from--;
  1242. } else {
  1243. html.push('<li class="page-first-separator disabled">',
  1244. '<a href="javascript:void(0)">...</a>',
  1245. '</li>');
  1246. }
  1247. to--;
  1248. }
  1249. }
  1250. if (this.totalPages >= 7) {
  1251. if (this.options.pageNumber >= (this.totalPages - 2)) {
  1252. from--;
  1253. }
  1254. }
  1255. if (this.totalPages == 6) {
  1256. if (this.options.pageNumber >= (this.totalPages - 2)) {
  1257. to++;
  1258. }
  1259. } else if (this.totalPages >= 7) {
  1260. if (this.totalPages == 7 || this.options.pageNumber >= (this.totalPages - 3)) {
  1261. to++;
  1262. }
  1263. }
  1264. for (i = from; i <= to; i++) {
  1265. html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
  1266. '<a href="javascript:void(0)">', i, '</a>',
  1267. '</li>');
  1268. }
  1269. if (this.totalPages >= 8) {
  1270. if (this.options.pageNumber <= (this.totalPages - 4)) {
  1271. html.push('<li class="page-last-separator disabled">',
  1272. '<a href="javascript:void(0)">...</a>',
  1273. '</li>');
  1274. }
  1275. }
  1276. if (this.totalPages >= 6) {
  1277. if (this.options.pageNumber <= (this.totalPages - 3)) {
  1278. html.push('<li class="page-last' + (this.totalPages === this.options.pageNumber ? ' active' : '') + '">',
  1279. '<a href="javascript:void(0)">', this.totalPages, '</a>',
  1280. '</li>');
  1281. }
  1282. }
  1283. html.push(
  1284. '<li class="page-next"><a href="javascript:void(0)">' + this.options.paginationNextText + '</a></li>',
  1285. '</ul>',
  1286. '</div>');
  1287. }
  1288. this.$pagination.html(html.join(''));
  1289. if (!this.options.onlyInfoPagination) {
  1290. $pageList = this.$pagination.find('.page-list a');
  1291. $first = this.$pagination.find('.page-first');
  1292. $pre = this.$pagination.find('.page-pre');
  1293. $next = this.$pagination.find('.page-next');
  1294. $last = this.$pagination.find('.page-last');
  1295. $number = this.$pagination.find('.page-number');
  1296. if (this.options.smartDisplay) {
  1297. if (this.totalPages <= 1) {
  1298. this.$pagination.find('div.pagination').hide();
  1299. }
  1300. if (pageList.length < 2 || this.options.totalRows <= pageList[0]) {
  1301. this.$pagination.find('span.page-list').hide();
  1302. }
  1303. // when data is empty, hide the pagination
  1304. this.$pagination[this.getData().length ? 'show' : 'hide']();
  1305. }
  1306. if ($allSelected) {
  1307. this.options.pageSize = this.options.formatAllRows();
  1308. }
  1309. $pageList.off('click').on('click', $.proxy(this.onPageListChange, this));
  1310. $first.off('click').on('click', $.proxy(this.onPageFirst, this));
  1311. $pre.off('click').on('click', $.proxy(this.onPagePre, this));
  1312. $next.off('click').on('click', $.proxy(this.onPageNext, this));
  1313. $last.off('click').on('click', $.proxy(this.onPageLast, this));
  1314. $number.off('click').on('click', $.proxy(this.onPageNumber, this));
  1315. }
  1316. };
  1317. BootstrapTable.prototype.updatePagination = function (event) {
  1318. // Fix #171: IE disabled button can be clicked bug.
  1319. if (event && $(event.currentTarget).hasClass('disabled')) {
  1320. return;
  1321. }
  1322. if (!this.options.maintainSelected) {
  1323. this.resetRows();
  1324. }
  1325. this.initPagination();
  1326. if (this.options.sidePagination === 'server') {
  1327. this.initServer();
  1328. } else {
  1329. this.initBody();
  1330. }
  1331. this.trigger('page-change', this.options.pageNumber, this.options.pageSize);
  1332. };
  1333. BootstrapTable.prototype.onPageListChange = function (event) {
  1334. var $this = $(event.currentTarget);
  1335. $this.parent().addClass('active').siblings().removeClass('active');
  1336. this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ?
  1337. this.options.formatAllRows() : +$this.text();
  1338. this.$toolbar.find('.page-size').text(this.options.pageSize);
  1339. this.updatePagination(event);
  1340. };
  1341. BootstrapTable.prototype.onPageFirst = function (event) {
  1342. this.options.pageNumber = 1;
  1343. this.updatePagination(event);
  1344. };
  1345. BootstrapTable.prototype.onPagePre = function (event) {
  1346. if ((this.options.pageNumber - 1) === 0) {
  1347. this.options.pageNumber = this.options.totalPages;
  1348. } else {
  1349. this.options.pageNumber--;
  1350. }
  1351. this.updatePagination(event);
  1352. };
  1353. BootstrapTable.prototype.onPageNext = function (event) {
  1354. if ((this.options.pageNumber + 1) > this.options.totalPages) {
  1355. this.options.pageNumber = 1;
  1356. } else {
  1357. this.options.pageNumber++;
  1358. }
  1359. this.updatePagination(event);
  1360. };
  1361. BootstrapTable.prototype.onPageLast = function (event) {
  1362. this.options.pageNumber = this.totalPages;
  1363. this.updatePagination(event);
  1364. };
  1365. BootstrapTable.prototype.onPageNumber = function (event) {
  1366. if (this.options.pageNumber === +$(event.currentTarget).text()) {
  1367. return;
  1368. }
  1369. this.options.pageNumber = +$(event.currentTarget).text();
  1370. this.updatePagination(event);
  1371. };
  1372. BootstrapTable.prototype.initBody = function (fixedScroll) {
  1373. var that = this,
  1374. html = [],
  1375. data = this.getData();
  1376. this.trigger('pre-body', data);
  1377. this.$body = this.$el.find('>tbody');
  1378. if (!this.$body.length) {
  1379. this.$body = $('<tbody></tbody>').appendTo(this.$el);
  1380. }
  1381. //Fix #389 Bootstrap-table-flatJSON is not working
  1382. if (!this.options.pagination || this.options.sidePagination === 'server') {
  1383. this.pageFrom = 1;
  1384. this.pageTo = data.length;
  1385. }
  1386. for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
  1387. var key,
  1388. item = data[i],
  1389. style = {},
  1390. csses = [],
  1391. data_ = '',
  1392. attributes = {},
  1393. htmlAttributes = [];
  1394. style = calculateObjectValue(this.options, this.options.rowStyle, [item, i], style);
  1395. if (style && style.css) {
  1396. for (key in style.css) {
  1397. csses.push(key + ': ' + style.css[key]);
  1398. }
  1399. }
  1400. attributes = calculateObjectValue(this.options,
  1401. this.options.rowAttributes, [item, i], attributes);
  1402. if (attributes) {
  1403. for (key in attributes) {
  1404. htmlAttributes.push(sprintf('%s="%s"', key, escapeHTML(attributes[key])));
  1405. }
  1406. }
  1407. if (item._data && !$.isEmptyObject(item._data)) {
  1408. $.each(item._data, function (k, v) {
  1409. // ignore data-index
  1410. if (k === 'index') {
  1411. return;
  1412. }
  1413. data_ += sprintf(' data-%s="%s"', k, v);
  1414. });
  1415. }
  1416. html.push('<tr',
  1417. sprintf(' %s', htmlAttributes.join(' ')),
  1418. sprintf(' id="%s"', $.isArray(item) ? undefined : item._id),
  1419. sprintf(' class="%s"', style.classes || ($.isArray(item) ? undefined : item._class)),
  1420. sprintf(' data-index="%s"', i),
  1421. sprintf(' data-uniqueid="%s"', item[this.options.uniqueId]),
  1422. sprintf('%s', data_),
  1423. '>'
  1424. );
  1425. if (this.options.cardView) {
  1426. html.push(sprintf('<td colspan="%s"><div class="card-views">', this.header.fields.length));
  1427. }
  1428. if (!this.options.cardView && this.options.detailView) {
  1429. html.push('<td>',
  1430. '<a class="detail-icon" href="javascript:">',
  1431. sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.detailOpen),
  1432. '</a>',
  1433. '</td>');
  1434. }
  1435. $.each(this.header.fields, function (j, field) {
  1436. var text = '',
  1437. value = getItemField(item, field, that.options.escape),
  1438. type = '',
  1439. cellStyle = {},
  1440. id_ = '',
  1441. class_ = that.header.classes[j],
  1442. data_ = '',
  1443. rowspan_ = '',
  1444. colspan_ = '',
  1445. title_ = '',
  1446. column = that.columns[j];
  1447. if (that.fromHtml && typeof value === 'undefined') {
  1448. return;
  1449. }
  1450. if (!column.visible) {
  1451. return;
  1452. }
  1453. if (that.options.cardView && (!column.cardVisible)) {
  1454. return;
  1455. }
  1456. style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
  1457. // handle td's id and class
  1458. if (item['_' + field + '_id']) {
  1459. id_ = sprintf(' id="%s"', item['_' + field + '_id']);
  1460. }
  1461. if (item['_' + field + '_class']) {
  1462. class_ = sprintf(' class="%s"', item['_' + field + '_class']);
  1463. }
  1464. if (item['_' + field + '_rowspan']) {
  1465. rowspan_ = sprintf(' rowspan="%s"', item['_' + field + '_rowspan']);
  1466. }
  1467. if (item['_' + field + '_colspan']) {
  1468. colspan_ = sprintf(' colspan="%s"', item['_' + field + '_colspan']);
  1469. }
  1470. if (item['_' + field + '_title']) {
  1471. title_ = sprintf(' title="%s"', item['_' + field + '_title']);
  1472. }
  1473. cellStyle = calculateObjectValue(that.header,
  1474. that.header.cellStyles[j], [value, item, i, field], cellStyle);
  1475. if (cellStyle.classes) {
  1476. class_ = sprintf(' class="%s"', cellStyle.classes);
  1477. }
  1478. if (cellStyle.css) {
  1479. var csses_ = [];
  1480. for (var key in cellStyle.css) {
  1481. csses_.push(key + ': ' + cellStyle.css[key]);
  1482. }
  1483. style = sprintf('style="%s"', csses_.concat(that.header.styles[j]).join('; '));
  1484. }
  1485. value = calculateObjectValue(column,
  1486. that.header.formatters[j], [value, item, i], value);
  1487. if (item['_' + field + '_data'] && !$.isEmptyObject(item['_' + field + '_data'])) {
  1488. $.each(item['_' + field + '_data'], function (k, v) {
  1489. // ignore data-index
  1490. if (k === 'index') {
  1491. return;
  1492. }
  1493. data_ += sprintf(' data-%s="%s"', k, v);
  1494. });
  1495. }
  1496. if (column.checkbox || column.radio) {
  1497. type = column.checkbox ? 'checkbox' : type;
  1498. type = column.radio ? 'radio' : type;
  1499. text = [sprintf(that.options.cardView ?
  1500. '<div class="card-view %s">' : '<td class="bs-checkbox %s">', column['class'] || ''),
  1501. '<input' +
  1502. sprintf(' data-index="%s"', i) +
  1503. sprintf(' name="%s"', that.options.selectItemName) +
  1504. sprintf(' type="%s"', type) +
  1505. sprintf(' value="%s"', item[that.options.idField]) +
  1506. sprintf(' checked="%s"', value === true ||
  1507. (value && value.checked) ? 'checked' : undefined) +
  1508. sprintf(' disabled="%s"', !column.checkboxEnabled ||
  1509. (value && value.disabled) ? 'disabled' : undefined) +
  1510. ' />',
  1511. that.header.formatters[j] && typeof value === 'string' ? value : '',
  1512. that.options.cardView ? '</div>' : '</td>'
  1513. ].join('');
  1514. item[that.header.stateField] = value === true || (value && value.checked);
  1515. } else {
  1516. value = typeof value === 'undefined' || value === null ?
  1517. that.options.undefinedText : value;
  1518. text = that.options.cardView ? ['<div class="card-view">',
  1519. that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style,
  1520. getPropertyFromOther(that.columns, 'field', 'title', field)) : '',
  1521. sprintf('<span class="value">%s</span>', value),
  1522. '</div>'
  1523. ].join('') : [sprintf('<td%s %s %s %s %s %s %s>',
  1524. id_, class_, style, data_, rowspan_, colspan_, title_),
  1525. value,
  1526. '</td>'
  1527. ].join('');
  1528. // Hide empty data on Card view when smartDisplay is set to true.
  1529. if (that.options.cardView && that.options.smartDisplay && value === '') {
  1530. // Should set a placeholder for event binding correct fieldIndex
  1531. text = '<div class="card-view"></div>';
  1532. }
  1533. }
  1534. html.push(text);
  1535. });
  1536. if (this.options.cardView) {
  1537. html.push('</div></td>');
  1538. }
  1539. html.push('</tr>');
  1540. }
  1541. // show no records
  1542. if (!html.length) {
  1543. html.push('<tr class="no-records-found">',
  1544. sprintf('<td colspan="%s">%s</td>',
  1545. this.$header.find('th').length, this.options.formatNoMatches()),
  1546. '</tr>');
  1547. }
  1548. this.$body.html(html.join(''));
  1549. if (!fixedScroll) {
  1550. this.scrollTo(0);
  1551. }
  1552. // click to select by column
  1553. this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', function (e) {
  1554. var $td = $(this),
  1555. $tr = $td.parent(),
  1556. item = that.data[$tr.data('index')],
  1557. index = $td[0].cellIndex,
  1558. fields = that.getVisibleFields(),
  1559. field = fields[that.options.detailView && !that.options.cardView ? index - 1 : index],
  1560. column = that.columns[getFieldIndex(that.columns, field)],
  1561. value = getItemField(item, field, that.options.escape);
  1562. if ($td.find('.detail-icon').length) {
  1563. return;
  1564. }
  1565. that.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td);
  1566. that.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr, field);
  1567. // if click to select - then trigger the checkbox/radio click
  1568. if (e.type === 'click' && that.options.clickToSelect && column.clickToSelect) {
  1569. var $selectItem = $tr.find(sprintf('[name="%s"]', that.options.selectItemName));
  1570. if ($selectItem.length) {
  1571. $selectItem[0].click(); // #144: .trigger('click') bug
  1572. }
  1573. }
  1574. });
  1575. this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', function () {
  1576. var $this = $(this),
  1577. $tr = $this.parent().parent(),
  1578. index = $tr.data('index'),
  1579. row = data[index]; // Fix #980 Detail view, when searching, returns wrong row
  1580. // remove and update
  1581. if ($tr.next().is('tr.detail-view')) {
  1582. $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailOpen));
  1583. $tr.next().remove();
  1584. that.trigger('collapse-row', index, row);
  1585. } else {
  1586. $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailClose));
  1587. $tr.after(sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.find('td').length));
  1588. var $element = $tr.next().find('td');
  1589. var content = calculateObjectValue(that.options, that.options.detailFormatter, [index, row, $element], '');
  1590. if($element.length === 1) {
  1591. $element.append(content);
  1592. }
  1593. that.trigger('expand-row', index, row, $element);
  1594. }
  1595. that.resetView();
  1596. });
  1597. this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
  1598. this.$selectItem.off('click').on('click', function (event) {
  1599. event.stopImmediatePropagation();
  1600. var $this = $(this),
  1601. checked = $this.prop('checked'),
  1602. row = that.data[$this.data('index')];
  1603. if (that.options.maintainSelected && $(this).is(':radio')) {
  1604. $.each(that.options.data, function (i, row) {
  1605. row[that.header.stateField] = false;
  1606. });
  1607. }
  1608. row[that.header.stateField] = checked;
  1609. if (that.options.singleSelect) {
  1610. that.$selectItem.not(this).each(function () {
  1611. that.data[$(this).data('index')][that.header.stateField] = false;
  1612. });
  1613. that.$selectItem.filter(':checked').not(this).prop('checked', false);
  1614. }
  1615. that.updateSelected();
  1616. that.trigger(checked ? 'check' : 'uncheck', row, $this);
  1617. });
  1618. $.each(this.header.events, function (i, events) {
  1619. if (!events) {
  1620. return;
  1621. }
  1622. // fix bug, if events is defined with namespace
  1623. if (typeof events === 'string') {
  1624. events = calculateObjectValue(null, events);
  1625. }
  1626. var field = that.header.fields[i],
  1627. fieldIndex = $.inArray(field, that.getVisibleFields());
  1628. if (that.options.detailView && !that.options.cardView) {
  1629. fieldIndex += 1;
  1630. }
  1631. for (var key in events) {
  1632. that.$body.find('>tr:not(.no-records-found)').each(function () {
  1633. var $tr = $(this),
  1634. $td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(fieldIndex),
  1635. index = key.indexOf(' '),
  1636. name = key.substring(0, index),
  1637. el = key.substring(index + 1),
  1638. func = events[key];
  1639. $td.find(el).off(name).on(name, function (e) {
  1640. var index = $tr.data('index'),
  1641. row = that.data[index],
  1642. value = row[field];
  1643. func.apply(this, [e, value, row, index]);
  1644. });
  1645. });
  1646. }
  1647. });
  1648. this.updateSelected();
  1649. this.resetView();
  1650. this.trigger('post-body', data);
  1651. };
  1652. BootstrapTable.prototype.initServer = function (silent, query, url) {
  1653. var that = this,
  1654. data = {},
  1655. params = {
  1656. searchText: this.searchText,
  1657. sortName: this.options.sortName,
  1658. sortOrder: this.options.sortOrder
  1659. },
  1660. request;
  1661. if (this.options.pagination) {
  1662. params.pageSize = this.options.pageSize === this.options.formatAllRows() ?
  1663. this.options.totalRows : this.options.pageSize;
  1664. params.pageNumber = this.options.pageNumber;
  1665. }
  1666. if (!(url || this.options.url) && !this.options.ajax) {
  1667. return;
  1668. }
  1669. if (this.options.queryParamsType === 'limit') {
  1670. params = {
  1671. search: params.searchText,
  1672. sort: params.sortName,
  1673. order: params.sortOrder
  1674. };
  1675. if (this.options.pagination) {
  1676. params.offset = this.options.pageSize === this.options.formatAllRows() ?
  1677. 0 : this.options.pageSize * (this.options.pageNumber - 1);
  1678. params.limit = this.options.pageSize === this.options.formatAllRows() ?
  1679. this.options.totalRows : this.options.pageSize;
  1680. }
  1681. }
  1682. if (!($.isEmptyObject(this.filterColumnsPartial))) {
  1683. params.filter = JSON.stringify(this.filterColumnsPartial, null);
  1684. }
  1685. data = calculateObjectValue(this.options, this.options.queryParams, [params], data);
  1686. $.extend(data, query || {});
  1687. // false to stop request
  1688. if (data === false) {
  1689. return;
  1690. }
  1691. if (!silent) {
  1692. this.$tableLoading.show();
  1693. }
  1694. request = $.extend({}, calculateObjectValue(null, this.options.ajaxOptions), {
  1695. type: this.options.method,
  1696. url: url || this.options.url,
  1697. data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
  1698. JSON.stringify(data) : data,
  1699. cache: this.options.cache,
  1700. contentType: this.options.contentType,
  1701. dataType: this.options.dataType,
  1702. success: function (res) {
  1703. res = calculateObjectValue(that.options, that.options.responseHandler, [res], res);
  1704. that.load(res);
  1705. that.trigger('load-success', res);
  1706. if (!silent) that.$tableLoading.hide();
  1707. },
  1708. error: function (res) {
  1709. that.trigger('load-error', res.status, res);
  1710. if (!silent) that.$tableLoading.hide();
  1711. }
  1712. });
  1713. if (this.options.ajax) {
  1714. calculateObjectValue(this, this.options.ajax, [request], null);
  1715. } else {
  1716. $.ajax(request);
  1717. }
  1718. };
  1719. BootstrapTable.prototype.initSearchText = function () {
  1720. if (this.options.search) {
  1721. if (this.options.searchText !== '') {
  1722. var $search = this.$toolbar.find('.search input');
  1723. $search.val(this.options.searchText);
  1724. this.onSearch({currentTarget: $search});
  1725. }
  1726. }
  1727. };
  1728. BootstrapTable.prototype.getCaret = function () {
  1729. var that = this;
  1730. $.each(this.$header.find('th'), function (i, th) {
  1731. $(th).find('.sortable').removeClass('desc asc').addClass($(th).data('field') === that.options.sortName ? that.options.sortOrder : 'both');
  1732. });
  1733. };
  1734. BootstrapTable.prototype.updateSelected = function () {
  1735. var checkAll = this.$selectItem.filter(':enabled').length &&
  1736. this.$selectItem.filter(':enabled').length ===
  1737. this.$selectItem.filter(':enabled').filter(':checked').length;
  1738. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll);
  1739. this.$selectItem.each(function () {
  1740. $(this).closest('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
  1741. });
  1742. };
  1743. BootstrapTable.prototype.updateRows = function () {
  1744. var that = this;
  1745. this.$selectItem.each(function () {
  1746. that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked');
  1747. });
  1748. };
  1749. BootstrapTable.prototype.resetRows = function () {
  1750. var that = this;
  1751. $.each(this.data, function (i, row) {
  1752. that.$selectAll.prop('checked', false);
  1753. that.$selectItem.prop('checked', false);
  1754. if (that.header.stateField) {
  1755. row[that.header.stateField] = false;
  1756. }
  1757. });
  1758. };
  1759. BootstrapTable.prototype.trigger = function (name) {
  1760. var args = Array.prototype.slice.call(arguments, 1);
  1761. name += '.bs.table';
  1762. this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
  1763. this.$el.trigger($.Event(name), args);
  1764. this.options.onAll(name, args);
  1765. this.$el.trigger($.Event('all.bs.table'), [name, args]);
  1766. };
  1767. BootstrapTable.prototype.resetHeader = function () {
  1768. // fix #61: the hidden table reset header bug.
  1769. // fix bug: get $el.css('width') error sometime (height = 500)
  1770. clearTimeout(this.timeoutId_);
  1771. this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0);
  1772. };
  1773. BootstrapTable.prototype.fitHeader = function () {
  1774. var that = this,
  1775. fixedBody,
  1776. scrollWidth,
  1777. focused,
  1778. focusedTemp;
  1779. if (that.$el.is(':hidden')) {
  1780. that.timeoutId_ = setTimeout($.proxy(that.fitHeader, that), 100);
  1781. return;
  1782. }
  1783. fixedBody = this.$tableBody.get(0);
  1784. scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
  1785. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
  1786. getScrollBarWidth() : 0;
  1787. this.$el.css('margin-top', -this.$header.outerHeight());
  1788. focused = $(':focus');
  1789. if (focused.length > 0) {
  1790. var $th = focused.parents('th');
  1791. if ($th.length > 0) {
  1792. var dataField = $th.attr('data-field');
  1793. if (dataField !== undefined) {
  1794. var $headerTh = this.$header.find("[data-field='" + dataField + "']");
  1795. if ($headerTh.length > 0) {
  1796. $headerTh.find(":input").addClass("focus-temp");
  1797. }
  1798. }
  1799. }
  1800. }
  1801. this.$header_ = this.$header.clone(true, true);
  1802. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
  1803. this.$tableHeader.css({
  1804. 'margin-right': scrollWidth
  1805. }).find('table').css('width', this.$el.outerWidth())
  1806. .html('').attr('class', this.$el.attr('class'))
  1807. .append(this.$header_);
  1808. focusedTemp = $('.focus-temp:visible:eq(0)');
  1809. if (focusedTemp.length > 0) {
  1810. focusedTemp.focus();
  1811. this.$header.find('.focus-temp').removeClass('focus-temp');
  1812. }
  1813. // fix bug: $.data() is not working as expected after $.append()
  1814. this.$header.find('th[data-field]').each(function (i) {
  1815. that.$header_.find(sprintf('th[data-field="%s"]', $(this).data('field'))).data($(this).data());
  1816. });
  1817. var visibleFields = this.getVisibleFields(),
  1818. $ths = this.$header_.find('th');
  1819. this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
  1820. var $this = $(this),
  1821. index = i;
  1822. if (that.options.detailView && !that.options.cardView) {
  1823. if (i === 0) {
  1824. that.$header_.find('th.detail').find('.fht-cell').width($this.innerWidth());
  1825. }
  1826. index = i - 1;
  1827. }
  1828. var $th = that.$header_.find(sprintf('th[data-field="%s"]', visibleFields[index]));
  1829. if ($th.length > 1) {
  1830. $th = $($ths[$this[0].cellIndex]);
  1831. }
  1832. $th.find('.fht-cell').width($this.innerWidth());
  1833. });
  1834. // horizontal scroll event
  1835. // TODO: it's probably better improving the layout than binding to scroll event
  1836. this.$tableBody.off('scroll').on('scroll', function () {
  1837. that.$tableHeader.scrollLeft($(this).scrollLeft());
  1838. if (that.options.showFooter && !that.options.cardView) {
  1839. that.$tableFooter.scrollLeft($(this).scrollLeft());
  1840. }
  1841. });
  1842. that.trigger('post-header');
  1843. };
  1844. BootstrapTable.prototype.resetFooter = function () {
  1845. var that = this,
  1846. data = that.getData(),
  1847. html = [];
  1848. if (!this.options.showFooter || this.options.cardView) { //do nothing
  1849. return;
  1850. }
  1851. if (!this.options.cardView && this.options.detailView) {
  1852. html.push('<td><div class="th-inner">&nbsp;</div><div class="fht-cell"></div></td>');
  1853. }
  1854. $.each(this.columns, function (i, column) {
  1855. var key,
  1856. falign = '', // footer align style
  1857. valign = '',
  1858. csses = [],
  1859. style = {},
  1860. class_ = sprintf(' class="%s"', column['class']);
  1861. if (!column.visible) {
  1862. return;
  1863. }
  1864. if (that.options.cardView && (!column.cardVisible)) {
  1865. return;
  1866. }
  1867. falign = sprintf('text-align: %s; ', column.falign ? column.falign : column.align);
  1868. valign = sprintf('vertical-align: %s; ', column.valign);
  1869. style = calculateObjectValue(null, that.options.footerStyle);
  1870. if (style && style.css) {
  1871. for (key in style.css) {
  1872. csses.push(key + ': ' + style.css[key]);
  1873. }
  1874. }
  1875. html.push('<td', class_, sprintf(' style="%s"', falign + valign + csses.concat().join('; ')), '>');
  1876. html.push('<div class="th-inner">');
  1877. html.push(calculateObjectValue(column, column.footerFormatter, [data], '&nbsp;') || '&nbsp;');
  1878. html.push('</div>');
  1879. html.push('<div class="fht-cell"></div>');
  1880. html.push('</div>');
  1881. html.push('</td>');
  1882. });
  1883. this.$tableFooter.find('tr').html(html.join(''));
  1884. this.$tableFooter.show();
  1885. clearTimeout(this.timeoutFooter_);
  1886. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this),
  1887. this.$el.is(':hidden') ? 100 : 0);
  1888. };
  1889. BootstrapTable.prototype.fitFooter = function () {
  1890. var that = this,
  1891. $footerTd,
  1892. elWidth,
  1893. scrollWidth;
  1894. clearTimeout(this.timeoutFooter_);
  1895. if (this.$el.is(':hidden')) {
  1896. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100);
  1897. return;
  1898. }
  1899. elWidth = this.$el.css('width');
  1900. scrollWidth = elWidth > this.$tableBody.width() ? getScrollBarWidth() : 0;
  1901. this.$tableFooter.css({
  1902. 'margin-right': scrollWidth
  1903. }).find('table').css('width', elWidth)
  1904. .attr('class', this.$el.attr('class'));
  1905. $footerTd = this.$tableFooter.find('td');
  1906. this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
  1907. var $this = $(this);
  1908. $footerTd.eq(i).find('.fht-cell').width($this.innerWidth());
  1909. });
  1910. };
  1911. BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
  1912. if (index === -1) {
  1913. return;
  1914. }
  1915. this.columns[index].visible = checked;
  1916. this.initHeader();
  1917. this.initSearch();
  1918. this.initPagination();
  1919. this.initBody();
  1920. if (this.options.showColumns) {
  1921. var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
  1922. if (needUpdate) {
  1923. $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
  1924. }
  1925. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  1926. $items.filter(':checked').prop('disabled', true);
  1927. }
  1928. }
  1929. };
  1930. BootstrapTable.prototype.toggleRow = function (index, uniqueId, visible) {
  1931. if (index === -1) {
  1932. return;
  1933. }
  1934. this.$body.find(typeof index !== 'undefined' ?
  1935. sprintf('tr[data-index="%s"]', index) :
  1936. sprintf('tr[data-uniqueid="%s"]', uniqueId))
  1937. [visible ? 'show' : 'hide']();
  1938. };
  1939. BootstrapTable.prototype.getVisibleFields = function () {
  1940. var that = this,
  1941. visibleFields = [];
  1942. $.each(this.header.fields, function (j, field) {
  1943. var column = that.columns[getFieldIndex(that.columns, field)];
  1944. if (!column.visible) {
  1945. return;
  1946. }
  1947. visibleFields.push(field);
  1948. });
  1949. return visibleFields;
  1950. };
  1951. // PUBLIC FUNCTION DEFINITION
  1952. // =======================
  1953. BootstrapTable.prototype.resetView = function (params) {
  1954. var padding = 0;
  1955. if (params && params.height) {
  1956. this.options.height = params.height;
  1957. }
  1958. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  1959. this.$selectItem.length === this.$selectItem.filter(':checked').length);
  1960. if (this.options.height) {
  1961. var toolbarHeight = getRealHeight(this.$toolbar),
  1962. paginationHeight = getRealHeight(this.$pagination),
  1963. height = this.options.height - toolbarHeight - paginationHeight;
  1964. this.$tableContainer.css('height', height + 'px');
  1965. }
  1966. if (this.options.cardView) {
  1967. // remove the element css
  1968. this.$el.css('margin-top', '0');
  1969. this.$tableContainer.css('padding-bottom', '0');
  1970. this.$tableFooter.hide();
  1971. return;
  1972. }
  1973. if (this.options.showHeader && this.options.height) {
  1974. this.$tableHeader.show();
  1975. this.resetHeader();
  1976. padding += this.$header.outerHeight();
  1977. } else {
  1978. this.$tableHeader.hide();
  1979. this.trigger('post-header');
  1980. }
  1981. if (this.options.showFooter) {
  1982. this.resetFooter();
  1983. if (this.options.height) {
  1984. padding += this.$tableFooter.outerHeight() + 1;
  1985. }
  1986. }
  1987. // Assign the correct sortable arrow
  1988. this.getCaret();
  1989. this.$tableContainer.css('padding-bottom', padding + 'px');
  1990. this.trigger('reset-view');
  1991. };
  1992. BootstrapTable.prototype.getData = function (useCurrentPage) {
  1993. return (this.searchText || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) ?
  1994. (useCurrentPage ? this.data.slice(this.pageFrom - 1, this.pageTo) : this.data) :
  1995. (useCurrentPage ? this.options.data.slice(this.pageFrom - 1, this.pageTo) : this.options.data);
  1996. };
  1997. BootstrapTable.prototype.load = function (data) {
  1998. var fixedScroll = false;
  1999. // #431: support pagination
  2000. if (this.options.sidePagination === 'server') {
  2001. this.options.totalRows = data.total;
  2002. fixedScroll = data.fixedScroll;
  2003. data = data[this.options.dataField];
  2004. } else if (!$.isArray(data)) { // support fixedScroll
  2005. fixedScroll = data.fixedScroll;
  2006. data = data.data;
  2007. }
  2008. this.initData(data);
  2009. this.initSearch();
  2010. this.initPagination();
  2011. this.initBody(fixedScroll);
  2012. };
  2013. BootstrapTable.prototype.append = function (data) {
  2014. this.initData(data, 'append');
  2015. this.initSearch();
  2016. this.initPagination();
  2017. this.initSort();
  2018. this.initBody(true);
  2019. };
  2020. BootstrapTable.prototype.prepend = function (data) {
  2021. this.initData(data, 'prepend');
  2022. this.initSearch();
  2023. this.initPagination();
  2024. this.initSort();
  2025. this.initBody(true);
  2026. };
  2027. BootstrapTable.prototype.remove = function (params) {
  2028. var len = this.options.data.length,
  2029. i, row;
  2030. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  2031. return;
  2032. }
  2033. for (i = len - 1; i >= 0; i--) {
  2034. row = this.options.data[i];
  2035. if (!row.hasOwnProperty(params.field)) {
  2036. continue;
  2037. }
  2038. if ($.inArray(row[params.field], params.values) !== -1) {
  2039. this.options.data.splice(i, 1);
  2040. }
  2041. }
  2042. if (len === this.options.data.length) {
  2043. return;
  2044. }
  2045. this.initSearch();
  2046. this.initPagination();
  2047. this.initSort();
  2048. this.initBody(true);
  2049. };
  2050. BootstrapTable.prototype.removeAll = function () {
  2051. if (this.options.data.length > 0) {
  2052. this.options.data.splice(0, this.options.data.length);
  2053. this.initSearch();
  2054. this.initPagination();
  2055. this.initBody(true);
  2056. }
  2057. };
  2058. BootstrapTable.prototype.getRowByUniqueId = function (id) {
  2059. var uniqueId = this.options.uniqueId,
  2060. len = this.options.data.length,
  2061. dataRow = null,
  2062. i, row, rowUniqueId;
  2063. for (i = len - 1; i >= 0; i--) {
  2064. row = this.options.data[i];
  2065. if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
  2066. rowUniqueId = row[uniqueId];
  2067. } else if(row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
  2068. rowUniqueId = row._data[uniqueId];
  2069. } else {
  2070. continue;
  2071. }
  2072. if (typeof rowUniqueId === 'string') {
  2073. id = id.toString();
  2074. } else if (typeof rowUniqueId === 'number') {
  2075. if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
  2076. id = parseInt(id);
  2077. } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
  2078. id = parseFloat(id);
  2079. }
  2080. }
  2081. if (rowUniqueId === id) {
  2082. dataRow = row;
  2083. break;
  2084. }
  2085. }
  2086. return dataRow;
  2087. };
  2088. BootstrapTable.prototype.removeByUniqueId = function (id) {
  2089. var len = this.options.data.length,
  2090. row = this.getRowByUniqueId(id);
  2091. if (row) {
  2092. this.options.data.splice(this.options.data.indexOf(row), 1);
  2093. }
  2094. if (len === this.options.data.length) {
  2095. return;
  2096. }
  2097. this.initSearch();
  2098. this.initPagination();
  2099. this.initBody(true);
  2100. };
  2101. BootstrapTable.prototype.updateByUniqueId = function (params) {
  2102. var that = this;
  2103. var allParams = $.isArray(params) ? params : [ params ];
  2104. $.each(allParams, function(i, params) {
  2105. var rowId;
  2106. if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
  2107. return;
  2108. }
  2109. rowId = $.inArray(that.getRowByUniqueId(params.id), that.options.data);
  2110. if (rowId === -1) {
  2111. return;
  2112. }
  2113. $.extend(that.options.data[rowId], params.row);
  2114. });
  2115. this.initSearch();
  2116. this.initSort();
  2117. this.initBody(true);
  2118. };
  2119. BootstrapTable.prototype.insertRow = function (params) {
  2120. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  2121. return;
  2122. }
  2123. this.data.splice(params.index, 0, params.row);
  2124. this.initSearch();
  2125. this.initPagination();
  2126. this.initSort();
  2127. this.initBody(true);
  2128. };
  2129. BootstrapTable.prototype.updateRow = function (params) {
  2130. var that = this;
  2131. var allParams = $.isArray(params) ? params : [ params ];
  2132. $.each(allParams, function(i, params) {
  2133. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  2134. return;
  2135. }
  2136. $.extend(that.options.data[params.index], params.row);
  2137. });
  2138. this.initSearch();
  2139. this.initSort();
  2140. this.initBody(true);
  2141. };
  2142. BootstrapTable.prototype.showRow = function (params) {
  2143. if (!params.hasOwnProperty('index') && !params.hasOwnProperty('uniqueId')) {
  2144. return;
  2145. }
  2146. this.toggleRow(params.index, params.uniqueId, true);
  2147. };
  2148. BootstrapTable.prototype.hideRow = function (params) {
  2149. if (!params.hasOwnProperty('index') && !params.hasOwnProperty('uniqueId')) {
  2150. return;
  2151. }
  2152. this.toggleRow(params.index, params.uniqueId, false);
  2153. };
  2154. BootstrapTable.prototype.getRowsHidden = function (show) {
  2155. var rows = $(this.$body[0]).children().filter(':hidden'),
  2156. i = 0;
  2157. if (show) {
  2158. for (; i < rows.length; i++) {
  2159. $(rows[i]).show();
  2160. }
  2161. }
  2162. return rows;
  2163. };
  2164. BootstrapTable.prototype.mergeCells = function (options) {
  2165. var row = options.index,
  2166. col = $.inArray(options.field, this.getVisibleFields()),
  2167. rowspan = options.rowspan || 1,
  2168. colspan = options.colspan || 1,
  2169. i, j,
  2170. $tr = this.$body.find('>tr'),
  2171. $td;
  2172. if (this.options.detailView && !this.options.cardView) {
  2173. col += 1;
  2174. }
  2175. $td = $tr.eq(row).find('>td').eq(col);
  2176. if (row < 0 || col < 0 || row >= this.data.length) {
  2177. return;
  2178. }
  2179. for (i = row; i < row + rowspan; i++) {
  2180. for (j = col; j < col + colspan; j++) {
  2181. $tr.eq(i).find('>td').eq(j).hide();
  2182. }
  2183. }
  2184. $td.attr('rowspan', rowspan).attr('colspan', colspan).show();
  2185. };
  2186. BootstrapTable.prototype.updateCell = function (params) {
  2187. if (!params.hasOwnProperty('index') ||
  2188. !params.hasOwnProperty('field') ||
  2189. !params.hasOwnProperty('value')) {
  2190. return;
  2191. }
  2192. this.data[params.index][params.field] = params.value;
  2193. if (params.reinit === false) {
  2194. return;
  2195. }
  2196. this.initSort();
  2197. this.initBody(true);
  2198. };
  2199. BootstrapTable.prototype.getOptions = function () {
  2200. return this.options;
  2201. };
  2202. BootstrapTable.prototype.getSelections = function () {
  2203. var that = this;
  2204. return $.grep(this.options.data, function (row) {
  2205. return row[that.header.stateField];
  2206. });
  2207. };
  2208. BootstrapTable.prototype.getAllSelections = function () {
  2209. var that = this;
  2210. return $.grep(this.options.data, function (row) {
  2211. return row[that.header.stateField];
  2212. });
  2213. };
  2214. BootstrapTable.prototype.checkAll = function () {
  2215. this.checkAll_(true);
  2216. };
  2217. BootstrapTable.prototype.uncheckAll = function () {
  2218. this.checkAll_(false);
  2219. };
  2220. BootstrapTable.prototype.checkInvert = function () {
  2221. var that = this;
  2222. var rows = that.$selectItem.filter(':enabled');
  2223. var checked = rows.filter(':checked');
  2224. rows.each(function() {
  2225. $(this).prop('checked', !$(this).prop('checked'));
  2226. });
  2227. that.updateRows();
  2228. that.updateSelected();
  2229. that.trigger('uncheck-some', checked);
  2230. checked = that.getSelections();
  2231. that.trigger('check-some', checked);
  2232. };
  2233. BootstrapTable.prototype.checkAll_ = function (checked) {
  2234. var rows;
  2235. if (!checked) {
  2236. rows = this.getSelections();
  2237. }
  2238. this.$selectAll.add(this.$selectAll_).prop('checked', checked);
  2239. this.$selectItem.filter(':enabled').prop('checked', checked);
  2240. this.updateRows();
  2241. if (checked) {
  2242. rows = this.getSelections();
  2243. }
  2244. this.trigger(checked ? 'check-all' : 'uncheck-all', rows);
  2245. };
  2246. BootstrapTable.prototype.check = function (index) {
  2247. this.check_(true, index);
  2248. };
  2249. BootstrapTable.prototype.uncheck = function (index) {
  2250. this.check_(false, index);
  2251. };
  2252. BootstrapTable.prototype.check_ = function (checked, index) {
  2253. var $el = this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  2254. this.data[index][this.header.stateField] = checked;
  2255. this.updateSelected();
  2256. this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el);
  2257. };
  2258. BootstrapTable.prototype.checkBy = function (obj) {
  2259. this.checkBy_(true, obj);
  2260. };
  2261. BootstrapTable.prototype.uncheckBy = function (obj) {
  2262. this.checkBy_(false, obj);
  2263. };
  2264. BootstrapTable.prototype.checkBy_ = function (checked, obj) {
  2265. if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
  2266. return;
  2267. }
  2268. var that = this,
  2269. rows = [];
  2270. $.each(this.options.data, function (index, row) {
  2271. if (!row.hasOwnProperty(obj.field)) {
  2272. return false;
  2273. }
  2274. if ($.inArray(row[obj.field], obj.values) !== -1) {
  2275. var $el = that.$selectItem.filter(':enabled')
  2276. .filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  2277. row[that.header.stateField] = checked;
  2278. rows.push(row);
  2279. that.trigger(checked ? 'check' : 'uncheck', row, $el);
  2280. }
  2281. });
  2282. this.updateSelected();
  2283. this.trigger(checked ? 'check-some' : 'uncheck-some', rows);
  2284. };
  2285. BootstrapTable.prototype.destroy = function () {
  2286. this.$el.insertBefore(this.$container);
  2287. $(this.options.toolbar).insertBefore(this.$el);
  2288. this.$container.next().remove();
  2289. this.$container.remove();
  2290. this.$el.html(this.$el_.html())
  2291. .css('margin-top', '0')
  2292. .attr('class', this.$el_.attr('class') || ''); // reset the class
  2293. };
  2294. BootstrapTable.prototype.showLoading = function () {
  2295. this.$tableLoading.show();
  2296. };
  2297. BootstrapTable.prototype.hideLoading = function () {
  2298. this.$tableLoading.hide();
  2299. };
  2300. BootstrapTable.prototype.togglePagination = function () {
  2301. this.options.pagination = !this.options.pagination;
  2302. var button = this.$toolbar.find('button[name="paginationSwitch"] i');
  2303. if (this.options.pagination) {
  2304. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown);
  2305. } else {
  2306. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp);
  2307. }
  2308. this.updatePagination();
  2309. };
  2310. BootstrapTable.prototype.refresh = function (params) {
  2311. if (params && params.url) {
  2312. this.options.pageNumber = 1;
  2313. }
  2314. this.initServer(params && params.silent, params && params.query, params && params.url);
  2315. this.trigger('refresh', params);
  2316. };
  2317. BootstrapTable.prototype.resetWidth = function () {
  2318. if (this.options.showHeader && this.options.height) {
  2319. this.fitHeader();
  2320. }
  2321. if (this.options.showFooter) {
  2322. this.fitFooter();
  2323. }
  2324. };
  2325. BootstrapTable.prototype.showColumn = function (field) {
  2326. this.toggleColumn(getFieldIndex(this.columns, field), true, true);
  2327. };
  2328. BootstrapTable.prototype.hideColumn = function (field) {
  2329. this.toggleColumn(getFieldIndex(this.columns, field), false, true);
  2330. };
  2331. BootstrapTable.prototype.getHiddenColumns = function () {
  2332. return $.grep(this.columns, function (column) {
  2333. return !column.visible;
  2334. });
  2335. };
  2336. BootstrapTable.prototype.getVisibleColumns = function () {
  2337. return $.grep(this.columns, function (column) {
  2338. return column.visible;
  2339. });
  2340. };
  2341. BootstrapTable.prototype.toggleAllColumns = function (visible) {
  2342. $.each(this.columns, function (i, column) {
  2343. this.columns[i].visible = visible;
  2344. });
  2345. this.initHeader();
  2346. this.initSearch();
  2347. this.initPagination();
  2348. this.initBody();
  2349. if (this.options.showColumns) {
  2350. var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
  2351. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  2352. $items.filter(':checked').prop('disabled', true);
  2353. }
  2354. }
  2355. };
  2356. BootstrapTable.prototype.showAllColumns = function () {
  2357. this.toggleAllColumns(true);
  2358. };
  2359. BootstrapTable.prototype.hideAllColumns = function () {
  2360. this.toggleAllColumns(false);
  2361. };
  2362. BootstrapTable.prototype.filterBy = function (columns) {
  2363. this.filterColumns = $.isEmptyObject(columns) ? {} : columns;
  2364. this.options.pageNumber = 1;
  2365. this.initSearch();
  2366. this.updatePagination();
  2367. };
  2368. BootstrapTable.prototype.scrollTo = function (value) {
  2369. if (typeof value === 'string') {
  2370. value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0;
  2371. }
  2372. if (typeof value === 'number') {
  2373. this.$tableBody.scrollTop(value);
  2374. }
  2375. if (typeof value === 'undefined') {
  2376. return this.$tableBody.scrollTop();
  2377. }
  2378. };
  2379. BootstrapTable.prototype.getScrollPosition = function () {
  2380. return this.scrollTo();
  2381. };
  2382. BootstrapTable.prototype.selectPage = function (page) {
  2383. if (page > 0 && page <= this.options.totalPages) {
  2384. this.options.pageNumber = page;
  2385. this.updatePagination();
  2386. }
  2387. };
  2388. BootstrapTable.prototype.prevPage = function () {
  2389. if (this.options.pageNumber > 1) {
  2390. this.options.pageNumber--;
  2391. this.updatePagination();
  2392. }
  2393. };
  2394. BootstrapTable.prototype.nextPage = function () {
  2395. if (this.options.pageNumber < this.options.totalPages) {
  2396. this.options.pageNumber++;
  2397. this.updatePagination();
  2398. }
  2399. };
  2400. BootstrapTable.prototype.toggleView = function () {
  2401. this.options.cardView = !this.options.cardView;
  2402. this.initHeader();
  2403. // Fixed remove toolbar when click cardView button.
  2404. //that.initToolbar();
  2405. this.initBody();
  2406. this.trigger('toggle', this.options.cardView);
  2407. };
  2408. BootstrapTable.prototype.refreshOptions = function (options) {
  2409. //If the objects are equivalent then avoid the call of destroy / init methods
  2410. if (compareObjects(this.options, options, true)) {
  2411. return;
  2412. }
  2413. this.options = $.extend(this.options, options);
  2414. this.trigger('refresh-options', this.options);
  2415. this.destroy();
  2416. this.init();
  2417. };
  2418. BootstrapTable.prototype.resetSearch = function (text) {
  2419. var $search = this.$toolbar.find('.search input');
  2420. $search.val(text || '');
  2421. this.onSearch({currentTarget: $search});
  2422. };
  2423. BootstrapTable.prototype.expandRow_ = function (expand, index) {
  2424. var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', index));
  2425. if ($tr.next().is('tr.detail-view') === (expand ? false : true)) {
  2426. $tr.find('> td > .detail-icon').click();
  2427. }
  2428. };
  2429. BootstrapTable.prototype.expandRow = function (index) {
  2430. this.expandRow_(true, index);
  2431. };
  2432. BootstrapTable.prototype.collapseRow = function (index) {
  2433. this.expandRow_(false, index);
  2434. };
  2435. BootstrapTable.prototype.expandAllRows = function (isSubTable) {
  2436. if (isSubTable) {
  2437. var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', 0)),
  2438. that = this,
  2439. detailIcon = null,
  2440. executeInterval = false,
  2441. idInterval = -1;
  2442. if (!$tr.next().is('tr.detail-view')) {
  2443. $tr.find('> td > .detail-icon').click();
  2444. executeInterval = true;
  2445. } else if (!$tr.next().next().is('tr.detail-view')) {
  2446. $tr.next().find(".detail-icon").click();
  2447. executeInterval = true;
  2448. }
  2449. if (executeInterval) {
  2450. try {
  2451. idInterval = setInterval(function () {
  2452. detailIcon = that.$body.find("tr.detail-view").last().find(".detail-icon");
  2453. if (detailIcon.length > 0) {
  2454. detailIcon.click();
  2455. } else {
  2456. clearInterval(idInterval);
  2457. }
  2458. }, 1);
  2459. } catch (ex) {
  2460. clearInterval(idInterval);
  2461. }
  2462. }
  2463. } else {
  2464. var trs = this.$body.children();
  2465. for (var i = 0; i < trs.length; i++) {
  2466. this.expandRow_(true, $(trs[i]).data("index"));
  2467. }
  2468. }
  2469. };
  2470. BootstrapTable.prototype.collapseAllRows = function (isSubTable) {
  2471. if (isSubTable) {
  2472. this.expandRow_(false, 0);
  2473. } else {
  2474. var trs = this.$body.children();
  2475. for (var i = 0; i < trs.length; i++) {
  2476. this.expandRow_(false, $(trs[i]).data("index"));
  2477. }
  2478. }
  2479. };
  2480. BootstrapTable.prototype.updateFormatText = function (name, text) {
  2481. if (this.options[sprintf('format%s', name)]) {
  2482. if (typeof text === 'string') {
  2483. this.options[sprintf('format%s', name)] = function () {
  2484. return text;
  2485. };
  2486. } else if (typeof text === 'function') {
  2487. this.options[sprintf('format%s', name)] = text;
  2488. }
  2489. }
  2490. this.initToolbar();
  2491. this.initPagination();
  2492. this.initBody();
  2493. };
  2494. // BOOTSTRAP TABLE PLUGIN DEFINITION
  2495. // =======================
  2496. var allowedMethods = [
  2497. 'getOptions',
  2498. 'getSelections', 'getAllSelections', 'getData',
  2499. 'load', 'append', 'prepend', 'remove', 'removeAll',
  2500. 'insertRow', 'updateRow', 'updateCell', 'updateByUniqueId', 'removeByUniqueId',
  2501. 'getRowByUniqueId', 'showRow', 'hideRow', 'getRowsHidden',
  2502. 'mergeCells',
  2503. 'checkAll', 'uncheckAll', 'checkInvert',
  2504. 'check', 'uncheck',
  2505. 'checkBy', 'uncheckBy',
  2506. 'refresh',
  2507. 'resetView',
  2508. 'resetWidth',
  2509. 'destroy',
  2510. 'showLoading', 'hideLoading',
  2511. 'showColumn', 'hideColumn', 'getHiddenColumns', 'getVisibleColumns',
  2512. 'showAllColumns', 'hideAllColumns',
  2513. 'filterBy',
  2514. 'scrollTo',
  2515. 'getScrollPosition',
  2516. 'selectPage', 'prevPage', 'nextPage',
  2517. 'togglePagination',
  2518. 'toggleView',
  2519. 'refreshOptions',
  2520. 'resetSearch',
  2521. 'expandRow', 'collapseRow', 'expandAllRows', 'collapseAllRows',
  2522. 'updateFormatText'
  2523. ];
  2524. $.fn.bootstrapTable = function (option) {
  2525. var value,
  2526. args = Array.prototype.slice.call(arguments, 1);
  2527. this.each(function () {
  2528. var $this = $(this),
  2529. data = $this.data('bootstrap.table'),
  2530. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
  2531. typeof option === 'object' && option);
  2532. if (typeof option === 'string') {
  2533. if ($.inArray(option, allowedMethods) < 0) {
  2534. throw new Error("Unknown method: " + option);
  2535. }
  2536. if (!data) {
  2537. return;
  2538. }
  2539. value = data[option].apply(data, args);
  2540. if (option === 'destroy') {
  2541. $this.removeData('bootstrap.table');
  2542. }
  2543. }
  2544. if (!data) {
  2545. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  2546. }
  2547. });
  2548. return typeof value === 'undefined' ? this : value;
  2549. };
  2550. $.fn.bootstrapTable.Constructor = BootstrapTable;
  2551. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
  2552. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
  2553. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES;
  2554. $.fn.bootstrapTable.methods = allowedMethods;
  2555. $.fn.bootstrapTable.utils = {
  2556. sprintf: sprintf,
  2557. getFieldIndex: getFieldIndex,
  2558. compareObjects: compareObjects,
  2559. calculateObjectValue: calculateObjectValue,
  2560. getItemField: getItemField,
  2561. objectKeys: objectKeys,
  2562. isIEBrowser: isIEBrowser
  2563. };
  2564. // BOOTSTRAP TABLE INIT
  2565. // =======================
  2566. $(function () {
  2567. $('[data-toggle="table"]').bootstrapTable();
  2568. });
  2569. })(jQuery);