bootstrap-table.js 107 KB

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