bootstrap-table.js 107 KB

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