bootstrap-table.js 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * version: 1.11.9
  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. escape : false
  478. };
  479. BootstrapTable.EVENTS = {
  480. 'all.bs.table': 'onAll',
  481. 'click-cell.bs.table': 'onClickCell',
  482. 'dbl-click-cell.bs.table': 'onDblClickCell',
  483. 'click-row.bs.table': 'onClickRow',
  484. 'dbl-click-row.bs.table': 'onDblClickRow',
  485. 'sort.bs.table': 'onSort',
  486. 'check.bs.table': 'onCheck',
  487. 'uncheck.bs.table': 'onUncheck',
  488. 'check-all.bs.table': 'onCheckAll',
  489. 'uncheck-all.bs.table': 'onUncheckAll',
  490. 'check-some.bs.table': 'onCheckSome',
  491. 'uncheck-some.bs.table': 'onUncheckSome',
  492. 'load-success.bs.table': 'onLoadSuccess',
  493. 'load-error.bs.table': 'onLoadError',
  494. 'column-switch.bs.table': 'onColumnSwitch',
  495. 'page-change.bs.table': 'onPageChange',
  496. 'search.bs.table': 'onSearch',
  497. 'toggle.bs.table': 'onToggle',
  498. 'pre-body.bs.table': 'onPreBody',
  499. 'post-body.bs.table': 'onPostBody',
  500. 'post-header.bs.table': 'onPostHeader',
  501. 'expand-row.bs.table': 'onExpandRow',
  502. 'collapse-row.bs.table': 'onCollapseRow',
  503. 'refresh-options.bs.table': 'onRefreshOptions',
  504. 'reset-view.bs.table': 'onResetView',
  505. 'refresh.bs.table': 'onRefresh'
  506. };
  507. BootstrapTable.prototype.init = function () {
  508. this.initLocale();
  509. this.initContainer();
  510. this.initTable();
  511. this.initHeader();
  512. this.initData();
  513. this.initHiddenRows();
  514. this.initFooter();
  515. this.initToolbar();
  516. this.initPagination();
  517. this.initBody();
  518. this.initSearchText();
  519. this.initServer();
  520. };
  521. BootstrapTable.prototype.initLocale = function () {
  522. if (this.options.locale) {
  523. var parts = this.options.locale.split(/-|_/);
  524. parts[0].toLowerCase();
  525. if (parts[1]) parts[1].toUpperCase();
  526. if ($.fn.bootstrapTable.locales[this.options.locale]) {
  527. // locale as requested
  528. $.extend(this.options, $.fn.bootstrapTable.locales[this.options.locale]);
  529. } else if ($.fn.bootstrapTable.locales[parts.join('-')]) {
  530. // locale with sep set to - (in case original was specified with _)
  531. $.extend(this.options, $.fn.bootstrapTable.locales[parts.join('-')]);
  532. } else if ($.fn.bootstrapTable.locales[parts[0]]) {
  533. // short locale language code (i.e. 'en')
  534. $.extend(this.options, $.fn.bootstrapTable.locales[parts[0]]);
  535. }
  536. }
  537. };
  538. BootstrapTable.prototype.initContainer = function () {
  539. this.$container = $([
  540. '<div class="bootstrap-table">',
  541. '<div class="fixed-table-toolbar"></div>',
  542. this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
  543. '<div class="fixed-table-pagination" style="clear: both;"></div>' :
  544. '',
  545. '<div class="fixed-table-container">',
  546. '<div class="fixed-table-header"><table></table></div>',
  547. '<div class="fixed-table-body">',
  548. '<div class="fixed-table-loading">',
  549. this.options.formatLoadingMessage(),
  550. '</div>',
  551. '</div>',
  552. '<div class="fixed-table-footer"><table><tr></tr></table></div>',
  553. this.options.paginationVAlign === 'bottom' || this.options.paginationVAlign === 'both' ?
  554. '<div class="fixed-table-pagination"></div>' :
  555. '',
  556. '</div>',
  557. '</div>'
  558. ].join(''));
  559. this.$container.insertAfter(this.$el);
  560. this.$tableContainer = this.$container.find('.fixed-table-container');
  561. this.$tableHeader = this.$container.find('.fixed-table-header');
  562. this.$tableBody = this.$container.find('.fixed-table-body');
  563. this.$tableLoading = this.$container.find('.fixed-table-loading');
  564. this.$tableFooter = this.$container.find('.fixed-table-footer');
  565. this.$toolbar = this.$container.find('.fixed-table-toolbar');
  566. this.$pagination = this.$container.find('.fixed-table-pagination');
  567. this.$tableBody.append(this.$el);
  568. this.$container.after('<div class="clearfix"></div>');
  569. this.$el.addClass(this.options.classes);
  570. if (this.options.striped) {
  571. this.$el.addClass('table-striped');
  572. }
  573. if ($.inArray('table-no-bordered', this.options.classes.split(' ')) !== -1) {
  574. this.$tableContainer.addClass('table-no-bordered');
  575. }
  576. };
  577. BootstrapTable.prototype.initTable = function () {
  578. var that = this,
  579. columns = [],
  580. data = [];
  581. this.$header = this.$el.find('>thead');
  582. if (!this.$header.length) {
  583. this.$header = $('<thead></thead>').appendTo(this.$el);
  584. }
  585. this.$header.find('tr').each(function () {
  586. var column = [];
  587. $(this).find('th').each(function () {
  588. // Fix #2014 - getFieldIndex and elsewhere assume this is string, causes issues if not
  589. if (typeof $(this).data('field') !== 'undefined') {
  590. $(this).data('field', $(this).data('field') + '');
  591. }
  592. column.push($.extend({}, {
  593. title: $(this).html(),
  594. 'class': $(this).attr('class'),
  595. titleTooltip: $(this).attr('title'),
  596. rowspan: $(this).attr('rowspan') ? +$(this).attr('rowspan') : undefined,
  597. colspan: $(this).attr('colspan') ? +$(this).attr('colspan') : undefined
  598. }, $(this).data()));
  599. });
  600. columns.push(column);
  601. });
  602. if (!$.isArray(this.options.columns[0])) {
  603. this.options.columns = [this.options.columns];
  604. }
  605. this.options.columns = $.extend(true, [], columns, this.options.columns);
  606. this.columns = [];
  607. setFieldIndex(this.options.columns);
  608. $.each(this.options.columns, function (i, columns) {
  609. $.each(columns, function (j, column) {
  610. column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column);
  611. if (typeof column.fieldIndex !== 'undefined') {
  612. that.columns[column.fieldIndex] = column;
  613. }
  614. that.options.columns[i][j] = column;
  615. });
  616. });
  617. // if options.data is setting, do not process tbody data
  618. if (this.options.data.length) {
  619. return;
  620. }
  621. var m = [];
  622. this.$el.find('>tbody>tr').each(function (y) {
  623. var row = {};
  624. // save tr's id, class and data-* attributes
  625. row._id = $(this).attr('id');
  626. row._class = $(this).attr('class');
  627. row._data = getRealDataAttr($(this).data());
  628. $(this).find('>td').each(function (x) {
  629. var $this = $(this),
  630. cspan = +$this.attr('colspan') || 1,
  631. rspan = +$this.attr('rowspan') || 1,
  632. tx, ty;
  633. for (; m[y] && m[y][x]; x++); //skip already occupied cells in current row
  634. for (tx = x; tx < x + cspan; tx++) { //mark matrix elements occupied by current cell with true
  635. for (ty = y; ty < y + rspan; ty++) {
  636. if (!m[ty]) { //fill missing rows
  637. m[ty] = [];
  638. }
  639. m[ty][tx] = true;
  640. }
  641. }
  642. var field = that.columns[x].field;
  643. row[field] = $(this).html();
  644. // save td's id, class and data-* attributes
  645. row['_' + field + '_id'] = $(this).attr('id');
  646. row['_' + field + '_class'] = $(this).attr('class');
  647. row['_' + field + '_rowspan'] = $(this).attr('rowspan');
  648. row['_' + field + '_colspan'] = $(this).attr('colspan');
  649. row['_' + field + '_title'] = $(this).attr('title');
  650. row['_' + field + '_data'] = getRealDataAttr($(this).data());
  651. });
  652. data.push(row);
  653. });
  654. this.options.data = data;
  655. if (data.length) this.fromHtml = true;
  656. };
  657. BootstrapTable.prototype.initHeader = function () {
  658. var that = this,
  659. visibleColumns = {},
  660. html = [];
  661. this.header = {
  662. fields: [],
  663. styles: [],
  664. classes: [],
  665. formatters: [],
  666. events: [],
  667. sorters: [],
  668. sortNames: [],
  669. cellStyles: [],
  670. searchables: []
  671. };
  672. $.each(this.options.columns, function (i, columns) {
  673. html.push('<tr>');
  674. if (i === 0 && !that.options.cardView && that.options.detailView) {
  675. html.push(sprintf('<th class="detail" rowspan="%s"><div class="fht-cell"></div></th>',
  676. that.options.columns.length));
  677. }
  678. $.each(columns, function (j, column) {
  679. var text = '',
  680. halign = '', // header align style
  681. align = '', // body align style
  682. style = '',
  683. class_ = sprintf(' class="%s"', column['class']),
  684. order = that.options.sortOrder || column.order,
  685. unitWidth = 'px',
  686. width = column.width;
  687. if (column.width !== undefined && (!that.options.cardView)) {
  688. if (typeof column.width === 'string') {
  689. if (column.width.indexOf('%') !== -1) {
  690. unitWidth = '%';
  691. }
  692. }
  693. }
  694. if (column.width && typeof column.width === 'string') {
  695. width = column.width.replace('%', '').replace('px', '');
  696. }
  697. halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align);
  698. align = sprintf('text-align: %s; ', column.align);
  699. style = sprintf('vertical-align: %s; ', column.valign);
  700. style += sprintf('width: %s; ', (column.checkbox || column.radio) && !width ?
  701. '36px' : (width ? width + unitWidth : undefined));
  702. if (typeof column.fieldIndex !== 'undefined') {
  703. that.header.fields[column.fieldIndex] = column.field;
  704. that.header.styles[column.fieldIndex] = align + style;
  705. that.header.classes[column.fieldIndex] = class_;
  706. that.header.formatters[column.fieldIndex] = column.formatter;
  707. that.header.events[column.fieldIndex] = column.events;
  708. that.header.sorters[column.fieldIndex] = column.sorter;
  709. that.header.sortNames[column.fieldIndex] = column.sortName;
  710. that.header.cellStyles[column.fieldIndex] = column.cellStyle;
  711. that.header.searchables[column.fieldIndex] = column.searchable;
  712. if (!column.visible) {
  713. return;
  714. }
  715. if (that.options.cardView && (!column.cardVisible)) {
  716. return;
  717. }
  718. visibleColumns[column.field] = column;
  719. }
  720. html.push('<th' + sprintf(' title="%s"', column.titleTooltip),
  721. column.checkbox || column.radio ?
  722. sprintf(' class="bs-checkbox %s"', column['class'] || '') :
  723. class_,
  724. sprintf(' style="%s"', halign + style),
  725. sprintf(' rowspan="%s"', column.rowspan),
  726. sprintf(' colspan="%s"', column.colspan),
  727. sprintf(' data-field="%s"', column.field),
  728. '>');
  729. html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ?
  730. 'sortable both' : ''));
  731. text = that.options.escape ? escapeHTML(column.title) : 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 || (text === '' && typeof this.searchText === 'undefined')) {
  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. if (column.escape) {
  1476. value_ = escapeHTML(value_);
  1477. }
  1478. style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
  1479. // handle td's id and class
  1480. if (item['_' + field + '_id']) {
  1481. id_ = sprintf(' id="%s"', item['_' + field + '_id']);
  1482. }
  1483. if (item['_' + field + '_class']) {
  1484. class_ = sprintf(' class="%s"', item['_' + field + '_class']);
  1485. }
  1486. if (item['_' + field + '_rowspan']) {
  1487. rowspan_ = sprintf(' rowspan="%s"', item['_' + field + '_rowspan']);
  1488. }
  1489. if (item['_' + field + '_colspan']) {
  1490. colspan_ = sprintf(' colspan="%s"', item['_' + field + '_colspan']);
  1491. }
  1492. if (item['_' + field + '_title']) {
  1493. title_ = sprintf(' title="%s"', item['_' + field + '_title']);
  1494. }
  1495. cellStyle = calculateObjectValue(that.header,
  1496. that.header.cellStyles[j], [value_, item, i, field], cellStyle);
  1497. if (cellStyle.classes) {
  1498. class_ = sprintf(' class="%s"', cellStyle.classes);
  1499. }
  1500. if (cellStyle.css) {
  1501. var csses_ = [];
  1502. for (var key in cellStyle.css) {
  1503. csses_.push(key + ': ' + cellStyle.css[key]);
  1504. }
  1505. style = sprintf('style="%s"', csses_.concat(that.header.styles[j]).join('; '));
  1506. }
  1507. value = calculateObjectValue(column,
  1508. that.header.formatters[j], [value_, item, i], value_);
  1509. if (item['_' + field + '_data'] && !$.isEmptyObject(item['_' + field + '_data'])) {
  1510. $.each(item['_' + field + '_data'], function(k, v) {
  1511. // ignore data-index
  1512. if (k === 'index') {
  1513. return;
  1514. }
  1515. data_ += sprintf(' data-%s="%s"', k, v);
  1516. });
  1517. }
  1518. if (column.checkbox || column.radio) {
  1519. type = column.checkbox ? 'checkbox' : type;
  1520. type = column.radio ? 'radio' : type;
  1521. text = [sprintf(that.options.cardView ?
  1522. '<div class="card-view %s">' : '<td class="bs-checkbox %s">', column['class'] || ''),
  1523. '<input' +
  1524. sprintf(' data-index="%s"', i) +
  1525. sprintf(' name="%s"', that.options.selectItemName) +
  1526. sprintf(' type="%s"', type) +
  1527. sprintf(' value="%s"', item[that.options.idField]) +
  1528. sprintf(' checked="%s"', value === true ||
  1529. (value_ || value && value.checked) ? 'checked' : undefined) +
  1530. sprintf(' disabled="%s"', !column.checkboxEnabled ||
  1531. (value && value.disabled) ? 'disabled' : undefined) +
  1532. ' />',
  1533. that.header.formatters[j] && typeof value === 'string' ? value : '',
  1534. that.options.cardView ? '</div>' : '</td>'
  1535. ].join('');
  1536. item[that.header.stateField] = value === true || (value && value.checked);
  1537. } else {
  1538. value = typeof value === 'undefined' || value === null ?
  1539. that.options.undefinedText : value;
  1540. text = that.options.cardView ? ['<div class="card-view">',
  1541. that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style,
  1542. getPropertyFromOther(that.columns, 'field', 'title', field)) : '',
  1543. sprintf('<span class="value">%s</span>', value),
  1544. '</div>'
  1545. ].join('') : [sprintf('<td%s %s %s %s %s %s %s>',
  1546. id_, class_, style, data_, rowspan_, colspan_, title_),
  1547. value,
  1548. '</td>'
  1549. ].join('');
  1550. // Hide empty data on Card view when smartDisplay is set to true.
  1551. if (that.options.cardView && that.options.smartDisplay && value === '') {
  1552. // Should set a placeholder for event binding correct fieldIndex
  1553. text = '<div class="card-view"></div>';
  1554. }
  1555. }
  1556. html.push(text);
  1557. });
  1558. if (this.options.cardView) {
  1559. html.push('</div></td>');
  1560. }
  1561. html.push('</tr>');
  1562. return html.join(' ');
  1563. };
  1564. BootstrapTable.prototype.initBody = function (fixedScroll) {
  1565. var that = this,
  1566. html = [],
  1567. data = this.getData();
  1568. this.trigger('pre-body', data);
  1569. this.$body = this.$el.find('>tbody');
  1570. if (!this.$body.length) {
  1571. this.$body = $('<tbody></tbody>').appendTo(this.$el);
  1572. }
  1573. //Fix #389 Bootstrap-table-flatJSON is not working
  1574. if (!this.options.pagination || this.options.sidePagination === 'server') {
  1575. this.pageFrom = 1;
  1576. this.pageTo = data.length;
  1577. }
  1578. var trFragments = $(document.createDocumentFragment());
  1579. var hasTr;
  1580. for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
  1581. var item = data[i];
  1582. var tr = this.initRow(item, i, data, trFragments);
  1583. hasTr = hasTr || !!tr;
  1584. if (tr&&tr!==true) {
  1585. trFragments.append(tr);
  1586. }
  1587. }
  1588. // show no records
  1589. if (!hasTr) {
  1590. trFragments.append('<tr class="no-records-found">' +
  1591. sprintf('<td colspan="%s">%s</td>',
  1592. this.$header.find('th').length,
  1593. this.options.formatNoMatches()) +
  1594. '</tr>');
  1595. }
  1596. this.$body.html(trFragments);
  1597. if (!fixedScroll) {
  1598. this.scrollTo(0);
  1599. }
  1600. // click to select by column
  1601. this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', function (e) {
  1602. var $td = $(this),
  1603. $tr = $td.parent(),
  1604. item = that.data[$tr.data('index')],
  1605. index = $td[0].cellIndex,
  1606. fields = that.getVisibleFields(),
  1607. field = fields[that.options.detailView && !that.options.cardView ? index - 1 : index],
  1608. column = that.columns[getFieldIndex(that.columns, field)],
  1609. value = getItemField(item, field, that.options.escape);
  1610. if ($td.find('.detail-icon').length) {
  1611. return;
  1612. }
  1613. that.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td);
  1614. that.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr, field);
  1615. // if click to select - then trigger the checkbox/radio click
  1616. if (e.type === 'click' && that.options.clickToSelect && column.clickToSelect) {
  1617. var $selectItem = $tr.find(sprintf('[name="%s"]', that.options.selectItemName));
  1618. if ($selectItem.length) {
  1619. $selectItem[0].click(); // #144: .trigger('click') bug
  1620. }
  1621. }
  1622. });
  1623. this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', function () {
  1624. var $this = $(this),
  1625. $tr = $this.parent().parent(),
  1626. index = $tr.data('index'),
  1627. row = data[index]; // Fix #980 Detail view, when searching, returns wrong row
  1628. // remove and update
  1629. if ($tr.next().is('tr.detail-view')) {
  1630. $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailOpen));
  1631. that.trigger('collapse-row', index, row);
  1632. $tr.next().remove();
  1633. } else {
  1634. $this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailClose));
  1635. $tr.after(sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.find('td').length));
  1636. var $element = $tr.next().find('td');
  1637. var content = calculateObjectValue(that.options, that.options.detailFormatter, [index, row, $element], '');
  1638. if($element.length === 1) {
  1639. $element.append(content);
  1640. }
  1641. that.trigger('expand-row', index, row, $element);
  1642. }
  1643. that.resetView();
  1644. return false;
  1645. });
  1646. this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
  1647. this.$selectItem.off('click').on('click', function (event) {
  1648. event.stopImmediatePropagation();
  1649. var $this = $(this),
  1650. checked = $this.prop('checked'),
  1651. row = that.data[$this.data('index')];
  1652. if (that.options.maintainSelected && $(this).is(':radio')) {
  1653. $.each(that.options.data, function (i, row) {
  1654. row[that.header.stateField] = false;
  1655. });
  1656. }
  1657. row[that.header.stateField] = checked;
  1658. if (that.options.singleSelect) {
  1659. that.$selectItem.not(this).each(function () {
  1660. that.data[$(this).data('index')][that.header.stateField] = false;
  1661. });
  1662. that.$selectItem.filter(':checked').not(this).prop('checked', false);
  1663. }
  1664. that.updateSelected();
  1665. that.trigger(checked ? 'check' : 'uncheck', row, $this);
  1666. });
  1667. $.each(this.header.events, function (i, events) {
  1668. if (!events) {
  1669. return;
  1670. }
  1671. // fix bug, if events is defined with namespace
  1672. if (typeof events === 'string') {
  1673. events = calculateObjectValue(null, events);
  1674. }
  1675. var field = that.header.fields[i],
  1676. fieldIndex = $.inArray(field, that.getVisibleFields());
  1677. if (that.options.detailView && !that.options.cardView) {
  1678. fieldIndex += 1;
  1679. }
  1680. for (var key in events) {
  1681. that.$body.find('>tr:not(.no-records-found)').each(function () {
  1682. var $tr = $(this),
  1683. $td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(fieldIndex),
  1684. index = key.indexOf(' '),
  1685. name = key.substring(0, index),
  1686. el = key.substring(index + 1),
  1687. func = events[key];
  1688. $td.find(el).off(name).on(name, function (e) {
  1689. var index = $tr.data('index'),
  1690. row = that.data[index],
  1691. value = row[field];
  1692. var props = field.split('.');
  1693. if(props.length > 1) {
  1694. value = row;
  1695. for (var prop_index = 0; prop_index < props.length; prop_index++) {
  1696. value = value[props[prop_index]];
  1697. }
  1698. }
  1699. func.apply(this, [e, value, row, index]);
  1700. });
  1701. });
  1702. }
  1703. });
  1704. this.updateSelected();
  1705. this.resetView();
  1706. this.trigger('post-body', data);
  1707. };
  1708. BootstrapTable.prototype.initServer = function (silent, query, url) {
  1709. var that = this,
  1710. data = {},
  1711. params = {
  1712. searchText: this.searchText,
  1713. sortName: this.options.sortName,
  1714. sortOrder: this.options.sortOrder
  1715. },
  1716. request;
  1717. if (this.options.pagination) {
  1718. params.pageSize = this.options.pageSize === this.options.formatAllRows() ?
  1719. this.options.totalRows : this.options.pageSize;
  1720. params.pageNumber = this.options.pageNumber;
  1721. }
  1722. if (!(url || this.options.url) && !this.options.ajax) {
  1723. return;
  1724. }
  1725. if (this.options.queryParamsType === 'limit') {
  1726. params = {
  1727. search: params.searchText,
  1728. sort: params.sortName,
  1729. order: params.sortOrder
  1730. };
  1731. if (this.options.pagination) {
  1732. params.offset = this.options.pageSize === this.options.formatAllRows() ?
  1733. 0 : this.options.pageSize * (this.options.pageNumber - 1);
  1734. params.limit = this.options.pageSize === this.options.formatAllRows() ?
  1735. this.options.totalRows : this.options.pageSize;
  1736. }
  1737. }
  1738. if (!($.isEmptyObject(this.filterColumnsPartial))) {
  1739. params.filter = JSON.stringify(this.filterColumnsPartial, null);
  1740. }
  1741. data = calculateObjectValue(this.options, this.options.queryParams, [params], data);
  1742. $.extend(data, query || {});
  1743. // false to stop request
  1744. if (data === false) {
  1745. return;
  1746. }
  1747. if (!silent) {
  1748. this.$tableLoading.show();
  1749. }
  1750. request = $.extend({}, calculateObjectValue(null, this.options.ajaxOptions), {
  1751. type: this.options.method,
  1752. url: url || this.options.url,
  1753. data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
  1754. JSON.stringify(data) : data,
  1755. cache: this.options.cache,
  1756. contentType: this.options.contentType,
  1757. dataType: this.options.dataType,
  1758. success: function (res) {
  1759. res = calculateObjectValue(that.options, that.options.responseHandler, [res], res);
  1760. that.load(res);
  1761. that.trigger('load-success', res);
  1762. if (!silent) that.$tableLoading.hide();
  1763. },
  1764. error: function (res) {
  1765. that.trigger('load-error', res.status, res);
  1766. if (!silent) that.$tableLoading.hide();
  1767. }
  1768. });
  1769. if (this.options.ajax) {
  1770. calculateObjectValue(this, this.options.ajax, [request], null);
  1771. } else {
  1772. if (this._xhr && this._xhr.readyState !== 4) {
  1773. this._xhr.abort();
  1774. }
  1775. this._xhr = $.ajax(request);
  1776. }
  1777. };
  1778. BootstrapTable.prototype.initSearchText = function () {
  1779. if (this.options.search) {
  1780. if (this.options.searchText !== '') {
  1781. var $search = this.$toolbar.find('.search input');
  1782. $search.val(this.options.searchText);
  1783. this.onSearch({currentTarget: $search});
  1784. }
  1785. }
  1786. };
  1787. BootstrapTable.prototype.getCaret = function () {
  1788. var that = this;
  1789. $.each(this.$header.find('th'), function (i, th) {
  1790. $(th).find('.sortable').removeClass('desc asc').addClass($(th).data('field') === that.options.sortName ? that.options.sortOrder : 'both');
  1791. });
  1792. };
  1793. BootstrapTable.prototype.updateSelected = function () {
  1794. var checkAll = this.$selectItem.filter(':enabled').length &&
  1795. this.$selectItem.filter(':enabled').length ===
  1796. this.$selectItem.filter(':enabled').filter(':checked').length;
  1797. this.$selectAll.add(this.$selectAll_).prop('checked', checkAll);
  1798. this.$selectItem.each(function () {
  1799. $(this).closest('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
  1800. });
  1801. };
  1802. BootstrapTable.prototype.updateRows = function () {
  1803. var that = this;
  1804. this.$selectItem.each(function () {
  1805. that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked');
  1806. });
  1807. };
  1808. BootstrapTable.prototype.resetRows = function () {
  1809. var that = this;
  1810. $.each(this.data, function (i, row) {
  1811. that.$selectAll.prop('checked', false);
  1812. that.$selectItem.prop('checked', false);
  1813. if (that.header.stateField) {
  1814. row[that.header.stateField] = false;
  1815. }
  1816. });
  1817. this.initHiddenRows();
  1818. };
  1819. BootstrapTable.prototype.trigger = function (name) {
  1820. var args = Array.prototype.slice.call(arguments, 1);
  1821. name += '.bs.table';
  1822. this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
  1823. this.$el.trigger($.Event(name), args);
  1824. this.options.onAll(name, args);
  1825. this.$el.trigger($.Event('all.bs.table'), [name, args]);
  1826. };
  1827. BootstrapTable.prototype.resetHeader = function () {
  1828. // fix #61: the hidden table reset header bug.
  1829. // fix bug: get $el.css('width') error sometime (height = 500)
  1830. clearTimeout(this.timeoutId_);
  1831. this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0);
  1832. };
  1833. BootstrapTable.prototype.fitHeader = function () {
  1834. var that = this,
  1835. fixedBody,
  1836. scrollWidth,
  1837. focused,
  1838. focusedTemp;
  1839. if (that.$el.is(':hidden')) {
  1840. that.timeoutId_ = setTimeout($.proxy(that.fitHeader, that), 100);
  1841. return;
  1842. }
  1843. fixedBody = this.$tableBody.get(0);
  1844. scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
  1845. fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
  1846. getScrollBarWidth() : 0;
  1847. this.$el.css('margin-top', -this.$header.outerHeight());
  1848. focused = $(':focus');
  1849. if (focused.length > 0) {
  1850. var $th = focused.parents('th');
  1851. if ($th.length > 0) {
  1852. var dataField = $th.attr('data-field');
  1853. if (dataField !== undefined) {
  1854. var $headerTh = this.$header.find("[data-field='" + dataField + "']");
  1855. if ($headerTh.length > 0) {
  1856. $headerTh.find(":input").addClass("focus-temp");
  1857. }
  1858. }
  1859. }
  1860. }
  1861. this.$header_ = this.$header.clone(true, true);
  1862. this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
  1863. this.$tableHeader.css({
  1864. 'margin-right': scrollWidth
  1865. }).find('table').css('width', this.$el.outerWidth())
  1866. .html('').attr('class', this.$el.attr('class'))
  1867. .append(this.$header_);
  1868. focusedTemp = $('.focus-temp:visible:eq(0)');
  1869. if (focusedTemp.length > 0) {
  1870. focusedTemp.focus();
  1871. this.$header.find('.focus-temp').removeClass('focus-temp');
  1872. }
  1873. // fix bug: $.data() is not working as expected after $.append()
  1874. this.$header.find('th[data-field]').each(function (i) {
  1875. that.$header_.find(sprintf('th[data-field="%s"]', $(this).data('field'))).data($(this).data());
  1876. });
  1877. var visibleFields = this.getVisibleFields(),
  1878. $ths = this.$header_.find('th');
  1879. this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
  1880. var $this = $(this),
  1881. index = i;
  1882. if (that.options.detailView && !that.options.cardView) {
  1883. if (i === 0) {
  1884. that.$header_.find('th.detail').find('.fht-cell').width($this.innerWidth());
  1885. }
  1886. index = i - 1;
  1887. }
  1888. var $th = that.$header_.find(sprintf('th[data-field="%s"]', visibleFields[index]));
  1889. if ($th.length > 1) {
  1890. $th = $($ths[$this[0].cellIndex]);
  1891. }
  1892. $th.find('.fht-cell').width($this.innerWidth());
  1893. });
  1894. // horizontal scroll event
  1895. // TODO: it's probably better improving the layout than binding to scroll event
  1896. this.$tableBody.off('scroll').on('scroll', function () {
  1897. that.$tableHeader.scrollLeft($(this).scrollLeft());
  1898. if (that.options.showFooter && !that.options.cardView) {
  1899. that.$tableFooter.scrollLeft($(this).scrollLeft());
  1900. }
  1901. });
  1902. that.trigger('post-header');
  1903. };
  1904. BootstrapTable.prototype.resetFooter = function () {
  1905. var that = this,
  1906. data = that.getData(),
  1907. html = [];
  1908. if (!this.options.showFooter || this.options.cardView) { //do nothing
  1909. return;
  1910. }
  1911. if (!this.options.cardView && this.options.detailView) {
  1912. html.push('<td><div class="th-inner">&nbsp;</div><div class="fht-cell"></div></td>');
  1913. }
  1914. $.each(this.columns, function (i, column) {
  1915. var key,
  1916. falign = '', // footer align style
  1917. valign = '',
  1918. csses = [],
  1919. style = {},
  1920. class_ = sprintf(' class="%s"', column['class']);
  1921. if (!column.visible) {
  1922. return;
  1923. }
  1924. if (that.options.cardView && (!column.cardVisible)) {
  1925. return;
  1926. }
  1927. falign = sprintf('text-align: %s; ', column.falign ? column.falign : column.align);
  1928. valign = sprintf('vertical-align: %s; ', column.valign);
  1929. style = calculateObjectValue(null, that.options.footerStyle);
  1930. if (style && style.css) {
  1931. for (key in style.css) {
  1932. csses.push(key + ': ' + style.css[key]);
  1933. }
  1934. }
  1935. html.push('<td', class_, sprintf(' style="%s"', falign + valign + csses.concat().join('; ')), '>');
  1936. html.push('<div class="th-inner">');
  1937. html.push(calculateObjectValue(column, column.footerFormatter, [data], '&nbsp;') || '&nbsp;');
  1938. html.push('</div>');
  1939. html.push('<div class="fht-cell"></div>');
  1940. html.push('</div>');
  1941. html.push('</td>');
  1942. });
  1943. this.$tableFooter.find('tr').html(html.join(''));
  1944. this.$tableFooter.show();
  1945. clearTimeout(this.timeoutFooter_);
  1946. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this),
  1947. this.$el.is(':hidden') ? 100 : 0);
  1948. };
  1949. BootstrapTable.prototype.fitFooter = function () {
  1950. var that = this,
  1951. $footerTd,
  1952. elWidth,
  1953. scrollWidth;
  1954. clearTimeout(this.timeoutFooter_);
  1955. if (this.$el.is(':hidden')) {
  1956. this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100);
  1957. return;
  1958. }
  1959. elWidth = this.$el.css('width');
  1960. scrollWidth = elWidth > this.$tableBody.width() ? getScrollBarWidth() : 0;
  1961. this.$tableFooter.css({
  1962. 'margin-right': scrollWidth
  1963. }).find('table').css('width', elWidth)
  1964. .attr('class', this.$el.attr('class'));
  1965. $footerTd = this.$tableFooter.find('td');
  1966. this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
  1967. var $this = $(this);
  1968. $footerTd.eq(i).find('.fht-cell').width($this.innerWidth());
  1969. });
  1970. };
  1971. BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
  1972. if (index === -1) {
  1973. return;
  1974. }
  1975. this.columns[index].visible = checked;
  1976. this.initHeader();
  1977. this.initSearch();
  1978. this.initPagination();
  1979. this.initBody();
  1980. if (this.options.showColumns) {
  1981. var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
  1982. if (needUpdate) {
  1983. $items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
  1984. }
  1985. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  1986. $items.filter(':checked').prop('disabled', true);
  1987. }
  1988. }
  1989. };
  1990. BootstrapTable.prototype.getVisibleFields = function () {
  1991. var that = this,
  1992. visibleFields = [];
  1993. $.each(this.header.fields, function (j, field) {
  1994. var column = that.columns[getFieldIndex(that.columns, field)];
  1995. if (!column.visible) {
  1996. return;
  1997. }
  1998. visibleFields.push(field);
  1999. });
  2000. return visibleFields;
  2001. };
  2002. // PUBLIC FUNCTION DEFINITION
  2003. // =======================
  2004. BootstrapTable.prototype.resetView = function (params) {
  2005. var padding = 0;
  2006. if (params && params.height) {
  2007. this.options.height = params.height;
  2008. }
  2009. this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
  2010. this.$selectItem.length === this.$selectItem.filter(':checked').length);
  2011. if (this.options.height) {
  2012. var toolbarHeight = this.$toolbar.outerHeight(true),
  2013. paginationHeight = this.$pagination.outerHeight(true),
  2014. height = this.options.height - toolbarHeight - paginationHeight;
  2015. this.$tableContainer.css('height', height + 'px');
  2016. }
  2017. if (this.options.cardView) {
  2018. // remove the element css
  2019. this.$el.css('margin-top', '0');
  2020. this.$tableContainer.css('padding-bottom', '0');
  2021. this.$tableFooter.hide();
  2022. return;
  2023. }
  2024. if (this.options.showHeader && this.options.height) {
  2025. this.$tableHeader.show();
  2026. this.resetHeader();
  2027. padding += this.$header.outerHeight();
  2028. } else {
  2029. this.$tableHeader.hide();
  2030. this.trigger('post-header');
  2031. }
  2032. if (this.options.showFooter) {
  2033. this.resetFooter();
  2034. if (this.options.height) {
  2035. padding += this.$tableFooter.outerHeight() + 1;
  2036. }
  2037. }
  2038. // Assign the correct sortable arrow
  2039. this.getCaret();
  2040. this.$tableContainer.css('padding-bottom', padding + 'px');
  2041. this.trigger('reset-view');
  2042. };
  2043. BootstrapTable.prototype.getData = function (useCurrentPage) {
  2044. return (this.searchText || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) ?
  2045. (useCurrentPage ? this.data.slice(this.pageFrom - 1, this.pageTo) : this.data) :
  2046. (useCurrentPage ? this.options.data.slice(this.pageFrom - 1, this.pageTo) : this.options.data);
  2047. };
  2048. BootstrapTable.prototype.load = function (data) {
  2049. var fixedScroll = false;
  2050. // #431: support pagination
  2051. if (this.options.sidePagination === 'server') {
  2052. this.options.totalRows = data[this.options.totalField];
  2053. fixedScroll = data.fixedScroll;
  2054. data = data[this.options.dataField];
  2055. } else if (!$.isArray(data)) { // support fixedScroll
  2056. fixedScroll = data.fixedScroll;
  2057. data = data.data;
  2058. }
  2059. this.initData(data);
  2060. this.initSearch();
  2061. this.initPagination();
  2062. this.initBody(fixedScroll);
  2063. };
  2064. BootstrapTable.prototype.append = function (data) {
  2065. this.initData(data, 'append');
  2066. this.initSearch();
  2067. this.initPagination();
  2068. this.initSort();
  2069. this.initBody(true);
  2070. };
  2071. BootstrapTable.prototype.prepend = function (data) {
  2072. this.initData(data, 'prepend');
  2073. this.initSearch();
  2074. this.initPagination();
  2075. this.initSort();
  2076. this.initBody(true);
  2077. };
  2078. BootstrapTable.prototype.remove = function (params) {
  2079. var len = this.options.data.length,
  2080. i, row;
  2081. if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
  2082. return;
  2083. }
  2084. for (i = len - 1; i >= 0; i--) {
  2085. row = this.options.data[i];
  2086. if (!row.hasOwnProperty(params.field)) {
  2087. continue;
  2088. }
  2089. if ($.inArray(row[params.field], params.values) !== -1) {
  2090. this.options.data.splice(i, 1);
  2091. if (this.options.sidePagination === 'server') {
  2092. this.options.totalRows -= 1;
  2093. }
  2094. }
  2095. }
  2096. if (len === this.options.data.length) {
  2097. return;
  2098. }
  2099. this.initSearch();
  2100. this.initPagination();
  2101. this.initSort();
  2102. this.initBody(true);
  2103. };
  2104. BootstrapTable.prototype.removeAll = function () {
  2105. if (this.options.data.length > 0) {
  2106. this.options.data.splice(0, this.options.data.length);
  2107. this.initSearch();
  2108. this.initPagination();
  2109. this.initBody(true);
  2110. }
  2111. };
  2112. BootstrapTable.prototype.getRowByUniqueId = function (id) {
  2113. var uniqueId = this.options.uniqueId,
  2114. len = this.options.data.length,
  2115. dataRow = null,
  2116. i, row, rowUniqueId;
  2117. for (i = len - 1; i >= 0; i--) {
  2118. row = this.options.data[i];
  2119. if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
  2120. rowUniqueId = row[uniqueId];
  2121. } else if(row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
  2122. rowUniqueId = row._data[uniqueId];
  2123. } else {
  2124. continue;
  2125. }
  2126. if (typeof rowUniqueId === 'string') {
  2127. id = id.toString();
  2128. } else if (typeof rowUniqueId === 'number') {
  2129. if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
  2130. id = parseInt(id);
  2131. } else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
  2132. id = parseFloat(id);
  2133. }
  2134. }
  2135. if (rowUniqueId === id) {
  2136. dataRow = row;
  2137. break;
  2138. }
  2139. }
  2140. return dataRow;
  2141. };
  2142. BootstrapTable.prototype.removeByUniqueId = function (id) {
  2143. var len = this.options.data.length,
  2144. row = this.getRowByUniqueId(id);
  2145. if (row) {
  2146. this.options.data.splice(this.options.data.indexOf(row), 1);
  2147. }
  2148. if (len === this.options.data.length) {
  2149. return;
  2150. }
  2151. this.initSearch();
  2152. this.initPagination();
  2153. this.initBody(true);
  2154. };
  2155. BootstrapTable.prototype.updateByUniqueId = function (params) {
  2156. var that = this;
  2157. var allParams = $.isArray(params) ? params : [ params ];
  2158. $.each(allParams, function(i, params) {
  2159. var rowId;
  2160. if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
  2161. return;
  2162. }
  2163. rowId = $.inArray(that.getRowByUniqueId(params.id), that.options.data);
  2164. if (rowId === -1) {
  2165. return;
  2166. }
  2167. $.extend(that.options.data[rowId], params.row);
  2168. });
  2169. this.initSearch();
  2170. this.initPagination();
  2171. this.initSort();
  2172. this.initBody(true);
  2173. };
  2174. BootstrapTable.prototype.insertRow = function (params) {
  2175. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  2176. return;
  2177. }
  2178. this.data.splice(params.index, 0, params.row);
  2179. this.initSearch();
  2180. this.initPagination();
  2181. this.initSort();
  2182. this.initBody(true);
  2183. };
  2184. BootstrapTable.prototype.updateRow = function (params) {
  2185. var that = this;
  2186. var allParams = $.isArray(params) ? params : [ params ];
  2187. $.each(allParams, function(i, params) {
  2188. if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
  2189. return;
  2190. }
  2191. $.extend(that.options.data[params.index], params.row);
  2192. });
  2193. this.initSearch();
  2194. this.initPagination();
  2195. this.initSort();
  2196. this.initBody(true);
  2197. };
  2198. BootstrapTable.prototype.initHiddenRows = function () {
  2199. this.hiddenRows = [];
  2200. };
  2201. BootstrapTable.prototype.showRow = function (params) {
  2202. this.toggleRow(params, true);
  2203. };
  2204. BootstrapTable.prototype.hideRow = function (params) {
  2205. this.toggleRow(params, false);
  2206. };
  2207. BootstrapTable.prototype.toggleRow = function (params, visible) {
  2208. var row, index;
  2209. if (params.hasOwnProperty('index')) {
  2210. row = this.getData()[params.index];
  2211. } else if (params.hasOwnProperty('uniqueId')) {
  2212. row = this.getRowByUniqueId(params.uniqueId);
  2213. }
  2214. if (!row) {
  2215. return;
  2216. }
  2217. index = $.inArray(row, this.hiddenRows);
  2218. if (!visible && index === -1) {
  2219. this.hiddenRows.push(row);
  2220. } else if (visible && index > -1) {
  2221. this.hiddenRows.splice(index, 1);
  2222. }
  2223. this.initBody(true);
  2224. };
  2225. BootstrapTable.prototype.getHiddenRows = function (show) {
  2226. var that = this,
  2227. data = this.getData(),
  2228. rows = [];
  2229. $.each(data, function (i, row) {
  2230. if ($.inArray(row, that.hiddenRows) > -1) {
  2231. rows.push(row);
  2232. }
  2233. });
  2234. this.hiddenRows = rows;
  2235. return rows;
  2236. };
  2237. BootstrapTable.prototype.mergeCells = function (options) {
  2238. var row = options.index,
  2239. col = $.inArray(options.field, this.getVisibleFields()),
  2240. rowspan = options.rowspan || 1,
  2241. colspan = options.colspan || 1,
  2242. i, j,
  2243. $tr = this.$body.find('>tr'),
  2244. $td;
  2245. if (this.options.detailView && !this.options.cardView) {
  2246. col += 1;
  2247. }
  2248. $td = $tr.eq(row).find('>td').eq(col);
  2249. if (row < 0 || col < 0 || row >= this.data.length) {
  2250. return;
  2251. }
  2252. for (i = row; i < row + rowspan; i++) {
  2253. for (j = col; j < col + colspan; j++) {
  2254. $tr.eq(i).find('>td').eq(j).hide();
  2255. }
  2256. }
  2257. $td.attr('rowspan', rowspan).attr('colspan', colspan).show();
  2258. };
  2259. BootstrapTable.prototype.updateCell = function (params) {
  2260. if (!params.hasOwnProperty('index') ||
  2261. !params.hasOwnProperty('field') ||
  2262. !params.hasOwnProperty('value')) {
  2263. return;
  2264. }
  2265. this.data[params.index][params.field] = params.value;
  2266. if (params.reinit === false) {
  2267. return;
  2268. }
  2269. this.initSort();
  2270. this.initBody(true);
  2271. };
  2272. BootstrapTable.prototype.getOptions = function () {
  2273. return this.options;
  2274. };
  2275. BootstrapTable.prototype.getSelections = function () {
  2276. var that = this;
  2277. return $.grep(this.options.data, function (row) {
  2278. // fix #2424: from html with checkbox
  2279. return row[that.header.stateField] === true;
  2280. });
  2281. };
  2282. BootstrapTable.prototype.getAllSelections = function () {
  2283. var that = this;
  2284. return $.grep(this.options.data, function (row) {
  2285. return row[that.header.stateField];
  2286. });
  2287. };
  2288. BootstrapTable.prototype.checkAll = function () {
  2289. this.checkAll_(true);
  2290. };
  2291. BootstrapTable.prototype.uncheckAll = function () {
  2292. this.checkAll_(false);
  2293. };
  2294. BootstrapTable.prototype.checkInvert = function () {
  2295. var that = this;
  2296. var rows = that.$selectItem.filter(':enabled');
  2297. var checked = rows.filter(':checked');
  2298. rows.each(function() {
  2299. $(this).prop('checked', !$(this).prop('checked'));
  2300. });
  2301. that.updateRows();
  2302. that.updateSelected();
  2303. that.trigger('uncheck-some', checked);
  2304. checked = that.getSelections();
  2305. that.trigger('check-some', checked);
  2306. };
  2307. BootstrapTable.prototype.checkAll_ = function (checked) {
  2308. var rows;
  2309. if (!checked) {
  2310. rows = this.getSelections();
  2311. }
  2312. this.$selectAll.add(this.$selectAll_).prop('checked', checked);
  2313. this.$selectItem.filter(':enabled').prop('checked', checked);
  2314. this.updateRows();
  2315. if (checked) {
  2316. rows = this.getSelections();
  2317. }
  2318. this.trigger(checked ? 'check-all' : 'uncheck-all', rows);
  2319. };
  2320. BootstrapTable.prototype.check = function (index) {
  2321. this.check_(true, index);
  2322. };
  2323. BootstrapTable.prototype.uncheck = function (index) {
  2324. this.check_(false, index);
  2325. };
  2326. BootstrapTable.prototype.check_ = function (checked, index) {
  2327. var $el = this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  2328. this.data[index][this.header.stateField] = checked;
  2329. this.updateSelected();
  2330. this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el);
  2331. };
  2332. BootstrapTable.prototype.checkBy = function (obj) {
  2333. this.checkBy_(true, obj);
  2334. };
  2335. BootstrapTable.prototype.uncheckBy = function (obj) {
  2336. this.checkBy_(false, obj);
  2337. };
  2338. BootstrapTable.prototype.checkBy_ = function (checked, obj) {
  2339. if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
  2340. return;
  2341. }
  2342. var that = this,
  2343. rows = [];
  2344. $.each(this.options.data, function (index, row) {
  2345. if (!row.hasOwnProperty(obj.field)) {
  2346. return false;
  2347. }
  2348. if ($.inArray(row[obj.field], obj.values) !== -1) {
  2349. var $el = that.$selectItem.filter(':enabled')
  2350. .filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
  2351. row[that.header.stateField] = checked;
  2352. rows.push(row);
  2353. that.trigger(checked ? 'check' : 'uncheck', row, $el);
  2354. }
  2355. });
  2356. this.updateSelected();
  2357. this.trigger(checked ? 'check-some' : 'uncheck-some', rows);
  2358. };
  2359. BootstrapTable.prototype.destroy = function () {
  2360. this.$el.insertBefore(this.$container);
  2361. $(this.options.toolbar).insertBefore(this.$el);
  2362. this.$container.next().remove();
  2363. this.$container.remove();
  2364. this.$el.html(this.$el_.html())
  2365. .css('margin-top', '0')
  2366. .attr('class', this.$el_.attr('class') || ''); // reset the class
  2367. };
  2368. BootstrapTable.prototype.showLoading = function () {
  2369. this.$tableLoading.show();
  2370. };
  2371. BootstrapTable.prototype.hideLoading = function () {
  2372. this.$tableLoading.hide();
  2373. };
  2374. BootstrapTable.prototype.togglePagination = function () {
  2375. this.options.pagination = !this.options.pagination;
  2376. var button = this.$toolbar.find('button[name="paginationSwitch"] i');
  2377. if (this.options.pagination) {
  2378. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown);
  2379. } else {
  2380. button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp);
  2381. }
  2382. this.updatePagination();
  2383. };
  2384. BootstrapTable.prototype.refresh = function (params) {
  2385. if (params && params.url) {
  2386. this.options.url = params.url;
  2387. }
  2388. if (params && params.pageNumber) {
  2389. this.options.pageNumber = params.pageNumber;
  2390. }
  2391. if (params && params.pageSize) {
  2392. this.options.pageSize = params.pageSize;
  2393. }
  2394. this.initServer(params && params.silent,
  2395. params && params.query, params && params.url);
  2396. this.trigger('refresh', params);
  2397. };
  2398. BootstrapTable.prototype.resetWidth = function () {
  2399. if (this.options.showHeader && this.options.height) {
  2400. this.fitHeader();
  2401. }
  2402. if (this.options.showFooter) {
  2403. this.fitFooter();
  2404. }
  2405. };
  2406. BootstrapTable.prototype.showColumn = function (field) {
  2407. this.toggleColumn(getFieldIndex(this.columns, field), true, true);
  2408. };
  2409. BootstrapTable.prototype.hideColumn = function (field) {
  2410. this.toggleColumn(getFieldIndex(this.columns, field), false, true);
  2411. };
  2412. BootstrapTable.prototype.getHiddenColumns = function () {
  2413. return $.grep(this.columns, function (column) {
  2414. return !column.visible;
  2415. });
  2416. };
  2417. BootstrapTable.prototype.getVisibleColumns = function () {
  2418. return $.grep(this.columns, function (column) {
  2419. return column.visible;
  2420. });
  2421. };
  2422. BootstrapTable.prototype.toggleAllColumns = function (visible) {
  2423. $.each(this.columns, function (i, column) {
  2424. this.columns[i].visible = visible;
  2425. });
  2426. this.initHeader();
  2427. this.initSearch();
  2428. this.initPagination();
  2429. this.initBody();
  2430. if (this.options.showColumns) {
  2431. var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
  2432. if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
  2433. $items.filter(':checked').prop('disabled', true);
  2434. }
  2435. }
  2436. };
  2437. BootstrapTable.prototype.showAllColumns = function () {
  2438. this.toggleAllColumns(true);
  2439. };
  2440. BootstrapTable.prototype.hideAllColumns = function () {
  2441. this.toggleAllColumns(false);
  2442. };
  2443. BootstrapTable.prototype.filterBy = function (columns) {
  2444. this.filterColumns = $.isEmptyObject(columns) ? {} : columns;
  2445. this.options.pageNumber = 1;
  2446. this.initSearch();
  2447. this.updatePagination();
  2448. };
  2449. BootstrapTable.prototype.scrollTo = function (value) {
  2450. if (typeof value === 'string') {
  2451. value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0;
  2452. }
  2453. if (typeof value === 'number') {
  2454. this.$tableBody.scrollTop(value);
  2455. }
  2456. if (typeof value === 'undefined') {
  2457. return this.$tableBody.scrollTop();
  2458. }
  2459. };
  2460. BootstrapTable.prototype.getScrollPosition = function () {
  2461. return this.scrollTo();
  2462. };
  2463. BootstrapTable.prototype.selectPage = function (page) {
  2464. if (page > 0 && page <= this.options.totalPages) {
  2465. this.options.pageNumber = page;
  2466. this.updatePagination();
  2467. }
  2468. };
  2469. BootstrapTable.prototype.prevPage = function () {
  2470. if (this.options.pageNumber > 1) {
  2471. this.options.pageNumber--;
  2472. this.updatePagination();
  2473. }
  2474. };
  2475. BootstrapTable.prototype.nextPage = function () {
  2476. if (this.options.pageNumber < this.options.totalPages) {
  2477. this.options.pageNumber++;
  2478. this.updatePagination();
  2479. }
  2480. };
  2481. BootstrapTable.prototype.toggleView = function () {
  2482. this.options.cardView = !this.options.cardView;
  2483. this.initHeader();
  2484. // Fixed remove toolbar when click cardView button.
  2485. //that.initToolbar();
  2486. this.initBody();
  2487. this.trigger('toggle', this.options.cardView);
  2488. };
  2489. BootstrapTable.prototype.refreshOptions = function (options) {
  2490. //If the objects are equivalent then avoid the call of destroy / init methods
  2491. if (compareObjects(this.options, options, true)) {
  2492. return;
  2493. }
  2494. this.options = $.extend(this.options, options);
  2495. this.trigger('refresh-options', this.options);
  2496. this.destroy();
  2497. this.init();
  2498. };
  2499. BootstrapTable.prototype.resetSearch = function (text) {
  2500. var $search = this.$toolbar.find('.search input');
  2501. $search.val(text || '');
  2502. this.onSearch({currentTarget: $search});
  2503. };
  2504. BootstrapTable.prototype.expandRow_ = function (expand, index) {
  2505. var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', index));
  2506. if ($tr.next().is('tr.detail-view') === (expand ? false : true)) {
  2507. $tr.find('> td > .detail-icon').click();
  2508. }
  2509. };
  2510. BootstrapTable.prototype.expandRow = function (index) {
  2511. this.expandRow_(true, index);
  2512. };
  2513. BootstrapTable.prototype.collapseRow = function (index) {
  2514. this.expandRow_(false, index);
  2515. };
  2516. BootstrapTable.prototype.expandAllRows = function (isSubTable) {
  2517. if (isSubTable) {
  2518. var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', 0)),
  2519. that = this,
  2520. detailIcon = null,
  2521. executeInterval = false,
  2522. idInterval = -1;
  2523. if (!$tr.next().is('tr.detail-view')) {
  2524. $tr.find('> td > .detail-icon').click();
  2525. executeInterval = true;
  2526. } else if (!$tr.next().next().is('tr.detail-view')) {
  2527. $tr.next().find(".detail-icon").click();
  2528. executeInterval = true;
  2529. }
  2530. if (executeInterval) {
  2531. try {
  2532. idInterval = setInterval(function () {
  2533. detailIcon = that.$body.find("tr.detail-view").last().find(".detail-icon");
  2534. if (detailIcon.length > 0) {
  2535. detailIcon.click();
  2536. } else {
  2537. clearInterval(idInterval);
  2538. }
  2539. }, 1);
  2540. } catch (ex) {
  2541. clearInterval(idInterval);
  2542. }
  2543. }
  2544. } else {
  2545. var trs = this.$body.children();
  2546. for (var i = 0; i < trs.length; i++) {
  2547. this.expandRow_(true, $(trs[i]).data("index"));
  2548. }
  2549. }
  2550. };
  2551. BootstrapTable.prototype.collapseAllRows = function (isSubTable) {
  2552. if (isSubTable) {
  2553. this.expandRow_(false, 0);
  2554. } else {
  2555. var trs = this.$body.children();
  2556. for (var i = 0; i < trs.length; i++) {
  2557. this.expandRow_(false, $(trs[i]).data("index"));
  2558. }
  2559. }
  2560. };
  2561. BootstrapTable.prototype.updateFormatText = function (name, text) {
  2562. if (this.options[sprintf('format%s', name)]) {
  2563. if (typeof text === 'string') {
  2564. this.options[sprintf('format%s', name)] = function () {
  2565. return text;
  2566. };
  2567. } else if (typeof text === 'function') {
  2568. this.options[sprintf('format%s', name)] = text;
  2569. }
  2570. }
  2571. this.initToolbar();
  2572. this.initPagination();
  2573. this.initBody();
  2574. };
  2575. // BOOTSTRAP TABLE PLUGIN DEFINITION
  2576. // =======================
  2577. var allowedMethods = [
  2578. 'getOptions',
  2579. 'getSelections', 'getAllSelections', 'getData',
  2580. 'load', 'append', 'prepend', 'remove', 'removeAll',
  2581. 'insertRow', 'updateRow', 'updateCell', 'updateByUniqueId', 'removeByUniqueId',
  2582. 'getRowByUniqueId', 'showRow', 'hideRow', 'getHiddenRows',
  2583. 'mergeCells',
  2584. 'checkAll', 'uncheckAll', 'checkInvert',
  2585. 'check', 'uncheck',
  2586. 'checkBy', 'uncheckBy',
  2587. 'refresh',
  2588. 'resetView',
  2589. 'resetWidth',
  2590. 'destroy',
  2591. 'showLoading', 'hideLoading',
  2592. 'showColumn', 'hideColumn', 'getHiddenColumns', 'getVisibleColumns',
  2593. 'showAllColumns', 'hideAllColumns',
  2594. 'filterBy',
  2595. 'scrollTo',
  2596. 'getScrollPosition',
  2597. 'selectPage', 'prevPage', 'nextPage',
  2598. 'togglePagination',
  2599. 'toggleView',
  2600. 'refreshOptions',
  2601. 'resetSearch',
  2602. 'expandRow', 'collapseRow', 'expandAllRows', 'collapseAllRows',
  2603. 'updateFormatText'
  2604. ];
  2605. $.fn.bootstrapTable = function (option) {
  2606. var value,
  2607. args = Array.prototype.slice.call(arguments, 1);
  2608. this.each(function () {
  2609. var $this = $(this),
  2610. data = $this.data('bootstrap.table'),
  2611. options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
  2612. typeof option === 'object' && option);
  2613. if (typeof option === 'string') {
  2614. if ($.inArray(option, allowedMethods) < 0) {
  2615. throw new Error("Unknown method: " + option);
  2616. }
  2617. if (!data) {
  2618. return;
  2619. }
  2620. value = data[option].apply(data, args);
  2621. if (option === 'destroy') {
  2622. $this.removeData('bootstrap.table');
  2623. }
  2624. }
  2625. if (!data) {
  2626. $this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
  2627. }
  2628. });
  2629. return typeof value === 'undefined' ? this : value;
  2630. };
  2631. $.fn.bootstrapTable.Constructor = BootstrapTable;
  2632. $.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
  2633. $.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
  2634. $.fn.bootstrapTable.locales = BootstrapTable.LOCALES;
  2635. $.fn.bootstrapTable.methods = allowedMethods;
  2636. $.fn.bootstrapTable.utils = {
  2637. sprintf: sprintf,
  2638. getFieldIndex: getFieldIndex,
  2639. compareObjects: compareObjects,
  2640. calculateObjectValue: calculateObjectValue,
  2641. getItemField: getItemField,
  2642. objectKeys: objectKeys,
  2643. isIEBrowser: isIEBrowser
  2644. };
  2645. // BOOTSTRAP TABLE INIT
  2646. // =======================
  2647. $(function () {
  2648. $('[data-toggle="table"]').bootstrapTable();
  2649. });
  2650. })(jQuery);