bootstrap-table-filter-control.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @version: v2.2.0
  5. */
  6. const Utils = $.fn.bootstrapTable.utils
  7. const UtilsFilterControl = {
  8. getOptionsFromSelectControl (selectControl) {
  9. return selectControl.get(selectControl.length - 1).options
  10. },
  11. hideUnusedSelectOptions (selectControl, uniqueValues) {
  12. const options = UtilsFilterControl.getOptionsFromSelectControl(
  13. selectControl
  14. )
  15. for (let i = 0; i < options.length; i++) {
  16. if (options[i].value !== '') {
  17. if (!uniqueValues.hasOwnProperty(options[i].value)) {
  18. selectControl
  19. .find(Utils.sprintf('option[value=\'%s\']', options[i].value))
  20. .hide()
  21. } else {
  22. selectControl
  23. .find(Utils.sprintf('option[value=\'%s\']', options[i].value))
  24. .show()
  25. }
  26. }
  27. }
  28. },
  29. addOptionToSelectControl (selectControl, _value, text, selected) {
  30. const value = $.trim(_value)
  31. const $selectControl = $(selectControl.get(selectControl.length - 1))
  32. if (
  33. !UtilsFilterControl.existOptionInSelectControl(selectControl, value)
  34. ) {
  35. const option = $(
  36. $('<option></option>')
  37. .attr('value', value)
  38. .text(
  39. $('<div />')
  40. .html(text)
  41. .text()
  42. )
  43. )
  44. if (value === selected) {
  45. option.attr('selected', true)
  46. }
  47. $selectControl.append(option)
  48. }
  49. },
  50. sortSelectControl (selectControl, orderBy) {
  51. const $selectControl = $(selectControl.get(selectControl.length - 1))
  52. const $opts = $selectControl.find('option:gt(0)')
  53. $opts.sort((a, b) => {
  54. return Utils.sort(a.textContent, b.textContent, orderBy === 'desc' ? -1 : 1)
  55. })
  56. $selectControl.find('option:gt(0)').remove()
  57. $selectControl.append($opts)
  58. },
  59. existOptionInSelectControl (selectControl, value) {
  60. const options = UtilsFilterControl.getOptionsFromSelectControl(
  61. selectControl
  62. )
  63. for (let i = 0; i < options.length; i++) {
  64. if (options[i].value === value.toString()) {
  65. // The value is not valid to add
  66. return true
  67. }
  68. }
  69. // If we get here, the value is valid to add
  70. return false
  71. },
  72. fixHeaderCSS ({ $tableHeader }) {
  73. $tableHeader.css('height', '77px')
  74. },
  75. getCurrentHeader ({ $header, options, $tableHeader }) {
  76. let header = $header
  77. if (options.height) {
  78. header = $tableHeader
  79. }
  80. return header
  81. },
  82. getCurrentSearchControls ({ options }) {
  83. let searchControls = 'select, input'
  84. if (options.height) {
  85. searchControls = 'table select, table input'
  86. }
  87. return searchControls
  88. },
  89. getCursorPosition (el) {
  90. if (Utils.isIEBrowser()) {
  91. if ($(el).is('input[type=text]')) {
  92. let pos = 0
  93. if ('selectionStart' in el) {
  94. pos = el.selectionStart
  95. } else if ('selection' in document) {
  96. el.focus()
  97. const Sel = document.selection.createRange()
  98. const SelLength = document.selection.createRange().text.length
  99. Sel.moveStart('character', -el.value.length)
  100. pos = Sel.text.length - SelLength
  101. }
  102. return pos
  103. }
  104. return -1
  105. }
  106. return -1
  107. },
  108. setCursorPosition (el) {
  109. $(el).val(el.value)
  110. },
  111. copyValues (that) {
  112. const header = UtilsFilterControl.getCurrentHeader(that)
  113. const searchControls = UtilsFilterControl.getCurrentSearchControls(that)
  114. that.options.valuesFilterControl = []
  115. header.find(searchControls).each(function () {
  116. that.options.valuesFilterControl.push({
  117. field: $(this)
  118. .closest('[data-field]')
  119. .data('field'),
  120. value: $(this).val(),
  121. position: UtilsFilterControl.getCursorPosition($(this).get(0)),
  122. hasFocus: $(this).is(':focus')
  123. })
  124. })
  125. },
  126. setValues (that) {
  127. let field = null
  128. let result = []
  129. const header = UtilsFilterControl.getCurrentHeader(that)
  130. const searchControls = UtilsFilterControl.getCurrentSearchControls(that)
  131. if (that.options.valuesFilterControl.length > 0) {
  132. // Callback to apply after settings fields values
  133. let fieldToFocusCallback = null
  134. header.find(searchControls).each(function (index, ele) {
  135. field = $(this)
  136. .closest('[data-field]')
  137. .data('field')
  138. result = that.options.valuesFilterControl.filter(valueObj => valueObj.field === field)
  139. if (result.length > 0) {
  140. $(this).val(result[0].value)
  141. if (result[0].hasFocus) {
  142. // set callback if the field had the focus.
  143. fieldToFocusCallback = ((fieldToFocus, carretPosition) => {
  144. // Closure here to capture the field and cursor position
  145. const closedCallback = () => {
  146. fieldToFocus.focus()
  147. UtilsFilterControl.setCursorPosition(fieldToFocus, carretPosition)
  148. }
  149. return closedCallback
  150. })($(this).get(0), result[0].position)
  151. }
  152. }
  153. })
  154. // Callback call.
  155. if (fieldToFocusCallback !== null) {
  156. fieldToFocusCallback()
  157. }
  158. }
  159. },
  160. collectBootstrapCookies () {
  161. const cookies = []
  162. const foundCookies = document.cookie.match(/(?:bs.table.)(\w*)/g)
  163. if (foundCookies) {
  164. $.each(foundCookies, (i, _cookie) => {
  165. let cookie = _cookie
  166. if (/./.test(cookie)) {
  167. cookie = cookie.split('.').pop()
  168. }
  169. if ($.inArray(cookie, cookies) === -1) {
  170. cookies.push(cookie)
  171. }
  172. })
  173. return cookies
  174. }
  175. },
  176. escapeID (id) {
  177. return String(id).replace(/(:|\.|\[|\]|,)/g, '\\$1')
  178. },
  179. isColumnSearchableViaSelect ({ filterControl, searchable }) {
  180. return filterControl &&
  181. filterControl.toLowerCase() === 'select' &&
  182. searchable
  183. },
  184. isFilterDataNotGiven ({ filterData }) {
  185. return filterData === undefined ||
  186. filterData.toLowerCase() === 'column'
  187. },
  188. hasSelectControlElement (selectControl) {
  189. return selectControl && selectControl.length > 0
  190. },
  191. initFilterSelectControls (that) {
  192. const data = that.data
  193. const itemsPerPage = that.pageTo < that.options.data.length ? that.options.data.length : that.pageTo
  194. const z = that.options.pagination
  195. ? that.options.sidePagination === 'server'
  196. ? that.pageTo
  197. : that.options.totalRows
  198. : that.pageTo
  199. $.each(that.header.fields, (j, field) => {
  200. const column = that.columns[that.fieldsColumnsIndex[field]]
  201. const selectControl = $(`.bootstrap-table-filter-control-${UtilsFilterControl.escapeID(column.field)}`)
  202. if (
  203. UtilsFilterControl.isColumnSearchableViaSelect(column) &&
  204. UtilsFilterControl.isFilterDataNotGiven(column) &&
  205. UtilsFilterControl.hasSelectControlElement(selectControl)
  206. ) {
  207. if (selectControl.get(selectControl.length - 1).options.length === 0) {
  208. // Added the default option
  209. UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder, column.filterDefault)
  210. }
  211. const uniqueValues = {}
  212. for (let i = 0; i < z; i++) {
  213. // Added a new value
  214. const fieldValue = data[i][field]
  215. const formattedValue = Utils.calculateObjectValue(that.header, that.header.formatters[j], [fieldValue, data[i], i], fieldValue)
  216. uniqueValues[formattedValue] = fieldValue
  217. }
  218. // eslint-disable-next-line guard-for-in
  219. for (const key in uniqueValues) {
  220. UtilsFilterControl.addOptionToSelectControl(selectControl, uniqueValues[key], key, column.filterDefault)
  221. }
  222. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  223. if (that.options.hideUnusedSelectOptions) {
  224. UtilsFilterControl.hideUnusedSelectOptions(selectControl, uniqueValues)
  225. }
  226. }
  227. })
  228. that.trigger('created-controls')
  229. },
  230. getFilterDataMethod (objFilterDataMethod, searchTerm) {
  231. const keys = Object.keys(objFilterDataMethod)
  232. for (let i = 0; i < keys.length; i++) {
  233. if (keys[i] === searchTerm) {
  234. return objFilterDataMethod[searchTerm]
  235. }
  236. }
  237. return null
  238. },
  239. createControls (that, header) {
  240. let addedFilterControl = false
  241. let isVisible
  242. let html
  243. $.each(that.columns, (i, column) => {
  244. isVisible = 'hidden'
  245. html = []
  246. if (!column.visible) {
  247. return
  248. }
  249. if (!column.filterControl) {
  250. html.push('<div class="no-filter-control"></div>')
  251. } else {
  252. html.push('<div class="filter-control">')
  253. const nameControl = column.filterControl.toLowerCase()
  254. if (column.searchable && that.options.filterTemplate[nameControl]) {
  255. addedFilterControl = true
  256. isVisible = 'visible'
  257. html.push(
  258. that.options.filterTemplate[nameControl](
  259. that,
  260. column.field,
  261. isVisible,
  262. column.filterControlPlaceholder
  263. ? column.filterControlPlaceholder
  264. : '',
  265. column.filterDefault
  266. )
  267. )
  268. if ('' !== column.filterDefault && 'undefined' !== typeof column.filterDefault) {
  269. if ($.isEmptyObject(that.filterColumnsPartial)) {
  270. that.filterColumnsPartial = {}
  271. }
  272. that.filterColumnsPartial[column.field] = column.filterDefault
  273. }
  274. }
  275. }
  276. $.each(header.children().children(), (i, tr) => {
  277. const $tr = $(tr)
  278. if ($tr.data('field') === column.field) {
  279. $tr.find('.fht-cell').append(html.join(''))
  280. return false
  281. }
  282. })
  283. if (
  284. column.filterData !== undefined &&
  285. column.filterData.toLowerCase() !== 'column'
  286. ) {
  287. const filterDataType = UtilsFilterControl.getFilterDataMethod(
  288. /* eslint-disable no-use-before-define */
  289. filterDataMethods,
  290. column.filterData.substring(0, column.filterData.indexOf(':'))
  291. )
  292. let filterDataSource
  293. let selectControl
  294. if (filterDataType !== null) {
  295. filterDataSource = column.filterData.substring(
  296. column.filterData.indexOf(':') + 1,
  297. column.filterData.length
  298. )
  299. selectControl = $(
  300. `.bootstrap-table-filter-control-${UtilsFilterControl.escapeID(column.field)}`
  301. )
  302. UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder, column.filterDefault)
  303. filterDataType(filterDataSource, selectControl, column.filterDefault)
  304. } else {
  305. throw new SyntaxError(
  306. 'Error. You should use any of these allowed filter data methods: var, json, url.' +
  307. ' Use like this: var: {key: "value"}'
  308. )
  309. }
  310. let variableValues
  311. let key
  312. // eslint-disable-next-line default-case
  313. switch (filterDataType) {
  314. case 'url':
  315. $.ajax({
  316. url: filterDataSource,
  317. dataType: 'json',
  318. success (data) {
  319. // eslint-disable-next-line guard-for-in
  320. for (const key in data) {
  321. UtilsFilterControl.addOptionToSelectControl(selectControl, key, data[key], column.filterDefault)
  322. }
  323. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  324. }
  325. })
  326. break
  327. case 'var':
  328. variableValues = window[filterDataSource]
  329. // eslint-disable-next-line guard-for-in
  330. for (key in variableValues) {
  331. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], column.filterDefault)
  332. }
  333. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  334. break
  335. case 'jso':
  336. variableValues = JSON.parse(filterDataSource)
  337. // eslint-disable-next-line guard-for-in
  338. for (key in variableValues) {
  339. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], column.filterDefault)
  340. }
  341. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  342. break
  343. }
  344. }
  345. })
  346. if (addedFilterControl) {
  347. header.off('keyup', 'input').on('keyup', 'input', (event, obj) => {
  348. // Simulate enter key action from clear button
  349. event.keyCode = obj ? obj.keyCode : event.keyCode
  350. if (that.options.searchOnEnterKey && event.keyCode !== 13) {
  351. return
  352. }
  353. if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
  354. return
  355. }
  356. const $currentTarget = $(event.currentTarget)
  357. if ($currentTarget.is(':checkbox') || $currentTarget.is(':radio')) {
  358. return
  359. }
  360. clearTimeout(event.currentTarget.timeoutId || 0)
  361. event.currentTarget.timeoutId = setTimeout(() => {
  362. that.onColumnSearch(event)
  363. }, that.options.searchTimeOut)
  364. })
  365. header.off('change', 'select').on('change', 'select', event => {
  366. if (that.options.searchOnEnterKey && event.keyCode !== 13) {
  367. return
  368. }
  369. if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
  370. return
  371. }
  372. clearTimeout(event.currentTarget.timeoutId || 0)
  373. event.currentTarget.timeoutId = setTimeout(() => {
  374. that.onColumnSearch(event)
  375. }, that.options.searchTimeOut)
  376. })
  377. header.off('mouseup', 'input').on('mouseup', 'input', function (event) {
  378. const $input = $(this)
  379. const oldValue = $input.val()
  380. if (oldValue === '') {
  381. return
  382. }
  383. setTimeout(() => {
  384. const newValue = $input.val()
  385. if (newValue === '') {
  386. clearTimeout(event.currentTarget.timeoutId || 0)
  387. event.currentTarget.timeoutId = setTimeout(() => {
  388. that.onColumnSearch(event)
  389. }, that.options.searchTimeOut)
  390. }
  391. }, 1)
  392. })
  393. if (header.find('.date-filter-control').length > 0) {
  394. $.each(that.columns, (i, { filterControl, field, filterDatepickerOptions }) => {
  395. if (
  396. filterControl !== undefined &&
  397. filterControl.toLowerCase() === 'datepicker'
  398. ) {
  399. header
  400. .find(
  401. `.date-filter-control.bootstrap-table-filter-control-${field}`
  402. )
  403. .datepicker(filterDatepickerOptions)
  404. .on('changeDate', (event) => {
  405. clearTimeout(event.currentTarget.timeoutId || 0)
  406. event.currentTarget.timeoutId = setTimeout(() => {
  407. that.onColumnSearch(event)
  408. }, that.options.searchTimeOut)
  409. })
  410. }
  411. })
  412. }
  413. if (that.options.sidePagination !== 'server') {
  414. header.find('[class*=\'bootstrap-table-filter-control\']').each((k, input) => {
  415. $(input).trigger('change')
  416. })
  417. }
  418. } else {
  419. header.find('.filterControl').hide()
  420. }
  421. },
  422. getDirectionOfSelectOptions (_alignment) {
  423. const alignment = _alignment === undefined ? 'left' : _alignment.toLowerCase()
  424. switch (alignment) {
  425. case 'left':
  426. return 'ltr'
  427. case 'right':
  428. return 'rtl'
  429. case 'auto':
  430. return 'auto'
  431. default:
  432. return 'ltr'
  433. }
  434. }
  435. }
  436. const filterDataMethods = {
  437. var (filterDataSource, selectControl, filterOrderBy, selected) {
  438. const variableValues = window[filterDataSource]
  439. // eslint-disable-next-line guard-for-in
  440. for (const key in variableValues) {
  441. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], selected)
  442. }
  443. UtilsFilterControl.sortSelectControl(selectControl, filterOrderBy)
  444. },
  445. url (filterDataSource, selectControl, filterOrderBy, selected) {
  446. $.ajax({
  447. url: filterDataSource,
  448. dataType: 'json',
  449. success (data) {
  450. // eslint-disable-next-line guard-for-in
  451. for (const key in data) {
  452. UtilsFilterControl.addOptionToSelectControl(selectControl, key, data[key], selected)
  453. }
  454. UtilsFilterControl.sortSelectControl(selectControl, filterOrderBy)
  455. }
  456. })
  457. },
  458. json (filterDataSource, selectControl, filterOrderBy, selected) {
  459. const variableValues = JSON.parse(filterDataSource)
  460. // eslint-disable-next-line guard-for-in
  461. for (const key in variableValues) {
  462. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], selected)
  463. }
  464. UtilsFilterControl.sortSelectControl(selectControl, filterOrderBy)
  465. }
  466. }
  467. $.extend($.fn.bootstrapTable.defaults, {
  468. filterControl: false,
  469. onColumnSearch (field, text) {
  470. return false
  471. },
  472. onCreatedControls () {
  473. return true
  474. },
  475. alignmentSelectControlOptions: undefined,
  476. filterTemplate: {
  477. input (that, field, isVisible, placeholder, value) {
  478. return Utils.sprintf(
  479. '<input type="text" class="form-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s" placeholder="%s" value="%s">',
  480. field,
  481. isVisible,
  482. 'undefined' === typeof placeholder ? '' : placeholder,
  483. 'undefined' === typeof value ? '' : value
  484. )
  485. },
  486. select ({ options }, field, isVisible) {
  487. return Utils.sprintf(
  488. '<select class="form-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s" dir="%s"></select>',
  489. field,
  490. isVisible,
  491. UtilsFilterControl.getDirectionOfSelectOptions(
  492. options.alignmentSelectControlOptions
  493. )
  494. )
  495. },
  496. datepicker (that, field, isVisible, value) {
  497. return Utils.sprintf(
  498. '<input type="text" class="form-control date-filter-control bootstrap-table-filter-control-%s" style="width: 100%; visibility: %s" value="%s">',
  499. field,
  500. isVisible,
  501. 'undefined' === typeof value ? '' : value
  502. )
  503. }
  504. },
  505. disableControlWhenSearch: false,
  506. searchOnEnterKey: false,
  507. // internal variables
  508. valuesFilterControl: []
  509. })
  510. $.extend($.fn.bootstrapTable.columnDefaults, {
  511. filterControl: undefined,
  512. filterData: undefined,
  513. filterDatepickerOptions: undefined,
  514. filterStrictSearch: false,
  515. filterStartsWithSearch: false,
  516. filterControlPlaceholder: '',
  517. filterDefault: '',
  518. filterOrderBy: 'asc' // asc || desc
  519. })
  520. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  521. 'column-search.bs.table': 'onColumnSearch',
  522. 'created-controls.bs.table': 'onCreatedControls'
  523. })
  524. $.extend($.fn.bootstrapTable.defaults.icons, {
  525. clear: {
  526. bootstrap3: 'glyphicon-trash icon-clear'
  527. }[$.fn.bootstrapTable.theme] || 'fa-trash'
  528. })
  529. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales)
  530. $.fn.bootstrapTable.methods.push('triggerSearch')
  531. $.fn.bootstrapTable.methods.push('clearFilterControl')
  532. $.BootstrapTable = class extends $.BootstrapTable {
  533. init () {
  534. // Make sure that the filterControl option is set
  535. if (this.options.filterControl) {
  536. const that = this
  537. // Make sure that the internal variables are set correctly
  538. this.options.valuesFilterControl = []
  539. this.$el
  540. .on('reset-view.bs.table', () => {
  541. // Create controls on $tableHeader if the height is set
  542. if (!that.options.height) {
  543. return
  544. }
  545. // Avoid recreate the controls
  546. if (
  547. that.$tableHeader.find('select').length > 0 ||
  548. that.$tableHeader.find('input').length > 0
  549. ) {
  550. return
  551. }
  552. UtilsFilterControl.createControls(that, that.$tableHeader)
  553. })
  554. .on('post-header.bs.table', () => {
  555. UtilsFilterControl.setValues(that)
  556. })
  557. .on('post-body.bs.table', () => {
  558. if (that.options.height) {
  559. UtilsFilterControl.fixHeaderCSS(that)
  560. }
  561. this.$tableLoading.css('top', this.$header.outerHeight() + 1)
  562. })
  563. .on('column-switch.bs.table', () => {
  564. UtilsFilterControl.setValues(that)
  565. })
  566. .on('load-success.bs.table', () => {
  567. that.EnableControls(true)
  568. })
  569. .on('load-error.bs.table', () => {
  570. that.EnableControls(true)
  571. })
  572. }
  573. super.init()
  574. }
  575. initHeader () {
  576. super.initHeader()
  577. if (!this.options.filterControl) {
  578. return
  579. }
  580. UtilsFilterControl.createControls(this, this.$header)
  581. }
  582. initBody () {
  583. super.initBody()
  584. UtilsFilterControl.initFilterSelectControls(this)
  585. }
  586. initSearch () {
  587. const that = this
  588. const fp = $.isEmptyObject(that.filterColumnsPartial)
  589. ? null
  590. : that.filterColumnsPartial
  591. if (fp === null || Object.keys(fp).length <= 1) {
  592. super.initSearch()
  593. }
  594. if (this.options.sidePagination === 'server') {
  595. return
  596. }
  597. if (fp === null) {
  598. return
  599. }
  600. // Check partial column filter
  601. that.data = fp
  602. ? that.options.data.filter((item, i) => {
  603. const itemIsExpected = []
  604. Object.keys(item).forEach((x, index) => {
  605. const key = that.header.fields[index]
  606. const thisColumn = that.columns[that.fieldsColumnsIndex[key]]
  607. const fval = (fp[key] || '').toLowerCase()
  608. let value = Utils.getItemField(item, key, false)
  609. if (fval === '') {
  610. itemIsExpected.push(true)
  611. } else {
  612. // Fix #142: search use formated data
  613. if (thisColumn && thisColumn.searchFormatter) {
  614. value = $.fn.bootstrapTable.utils.calculateObjectValue(
  615. that.header,
  616. that.header.formatters[$.inArray(key, that.header.fields)],
  617. [value, item, i],
  618. value
  619. )
  620. }
  621. if ($.inArray(key, that.header.fields) !== -1) {
  622. if (value === undefined || value === null) {
  623. itemIsExpected.push(false)
  624. } else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  625. if (thisColumn.filterStrictSearch) {
  626. itemIsExpected.push(value.toString().toLowerCase() === fval.toString().toLowerCase())
  627. } else if (thisColumn.filterStartsWithSearch) {
  628. itemIsExpected.push((`${value}`).toLowerCase().indexOf(fval) === 0)
  629. } else {
  630. itemIsExpected.push((`${value}`).toLowerCase().includes(fval))
  631. }
  632. }
  633. }
  634. }
  635. })
  636. return !itemIsExpected.includes(false)
  637. })
  638. : that.data
  639. }
  640. initColumnSearch (filterColumnsDefaults) {
  641. UtilsFilterControl.copyValues(this)
  642. if (filterColumnsDefaults) {
  643. this.filterColumnsPartial = filterColumnsDefaults
  644. this.updatePagination()
  645. // eslint-disable-next-line guard-for-in
  646. for (const filter in filterColumnsDefaults) {
  647. this.trigger('column-search', filter, filterColumnsDefaults[filter])
  648. }
  649. }
  650. }
  651. onColumnSearch (event) {
  652. if ($.inArray(event.keyCode, [37, 38, 39, 40]) > -1) {
  653. return
  654. }
  655. UtilsFilterControl.copyValues(this)
  656. const text = $.trim($(event.currentTarget).val())
  657. const $field = $(event.currentTarget)
  658. .closest('[data-field]')
  659. .data('field')
  660. if ($.isEmptyObject(this.filterColumnsPartial)) {
  661. this.filterColumnsPartial = {}
  662. }
  663. if (text) {
  664. this.filterColumnsPartial[$field] = text
  665. } else {
  666. delete this.filterColumnsPartial[$field]
  667. }
  668. this.options.pageNumber = 1
  669. this.EnableControls(false)
  670. this.onSearch()
  671. this.trigger('column-search', $field, text)
  672. }
  673. resetSearch () {
  674. if (this.options.filterControl && this.options.showSearchClearButton) {
  675. this.clearFilterControl()
  676. }
  677. super.resetSearch()
  678. }
  679. clearFilterControl () {
  680. if (this.options.filterControl) {
  681. const that = this
  682. const cookies = UtilsFilterControl.collectBootstrapCookies()
  683. const header = UtilsFilterControl.getCurrentHeader(that)
  684. const table = header.closest('table')
  685. const controls = header.find(UtilsFilterControl.getCurrentSearchControls(that))
  686. const search = that.$toolbar.find('.search input')
  687. let hasValues = false
  688. let timeoutId = 0
  689. $.each(that.options.valuesFilterControl, (i, item) => {
  690. hasValues = hasValues ? true : item.value !== ''
  691. item.value = ''
  692. })
  693. $.each(that.options.filterControls, (i, item) => {
  694. item.text = ''
  695. })
  696. UtilsFilterControl.setValues(that)
  697. // clear cookies once the filters are clean
  698. clearTimeout(timeoutId)
  699. timeoutId = setTimeout(() => {
  700. if (cookies && cookies.length > 0) {
  701. $.each(cookies, (i, item) => {
  702. if (that.deleteCookie !== undefined) {
  703. that.deleteCookie(item)
  704. }
  705. })
  706. }
  707. }, that.options.searchTimeOut)
  708. // If there is not any value in the controls exit this method
  709. if (!hasValues) {
  710. return
  711. }
  712. // Clear each type of filter if it exists.
  713. // Requires the body to reload each time a type of filter is found because we never know
  714. // which ones are going to be present.
  715. if (controls.length > 0) {
  716. this.filterColumnsPartial = {}
  717. $(controls[0]).trigger(
  718. controls[0].tagName === 'INPUT' ? 'keyup' : 'change', { keyCode: 13 }
  719. )
  720. } else {
  721. return
  722. }
  723. if (search.length > 0) {
  724. that.resetSearch()
  725. }
  726. // use the default sort order if it exists. do nothing if it does not
  727. if (
  728. that.options.sortName !== table.data('sortName') ||
  729. that.options.sortOrder !== table.data('sortOrder')
  730. ) {
  731. const sorter = header.find(
  732. Utils.sprintf(
  733. '[data-field="%s"]',
  734. $(controls[0])
  735. .closest('table')
  736. .data('sortName')
  737. )
  738. )
  739. if (sorter.length > 0) {
  740. that.onSort({ type: 'keypress', currentTarget: sorter })
  741. $(sorter)
  742. .find('.sortable')
  743. .trigger('click')
  744. }
  745. }
  746. }
  747. }
  748. triggerSearch () {
  749. const header = UtilsFilterControl.getCurrentHeader(this)
  750. const searchControls = UtilsFilterControl.getCurrentSearchControls(this)
  751. header.find(searchControls).each(function () {
  752. const el = $(this)
  753. if (el.is('select')) {
  754. el.change()
  755. } else {
  756. el.keyup()
  757. }
  758. })
  759. }
  760. EnableControls (enable) {
  761. if (
  762. this.options.disableControlWhenSearch &&
  763. this.options.sidePagination === 'server'
  764. ) {
  765. const header = UtilsFilterControl.getCurrentHeader(this)
  766. const searchControls = UtilsFilterControl.getCurrentSearchControls(this)
  767. if (!enable) {
  768. header.find(searchControls).prop('disabled', 'disabled')
  769. } else {
  770. header.find(searchControls).removeProp('disabled')
  771. }
  772. }
  773. }
  774. }