yadcf
Version:
This jQuery plug-in allows the user to easily add filter components to table columns, the plug-in works on top of the DataTables jQuery plug-in.
1,063 lines (948 loc) • 260 kB
JavaScript
/*!
* Yet Another DataTables Column Filter - (yadcf)
*
* File: jquery.dataTables.yadcf.js
* Version: 0.9.6
*
* Author: Daniel Reznick
* Info: https://github.com/vedmack/yadcf
* Contact: vedmack@gmail.com
* Twitter: @danielreznick
* Q&A http://stackoverflow.com/questions/tagged/yadcf
*
* Copyright 2015 Daniel Reznick, all rights reserved.
* Copyright 2015 Released under the MIT License
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*/
/*
* Parameters:
*
*
* -------------
* column_number
Required: true (or use column_selector)
Type: int
Description: The number of the column to which the filter will be applied
* column_selector
Required: true (or use column_number)
Type: see https://datatables.net/reference/type/column-selector for valid column-selector formats
Description: The column-selector of the column to which the filter will be applied
* filter_type
Required: false
Type: String
Default value: 'select'
Possible values: select / multi_select / auto_complete / text / date / range_number / range_number_slider / range_date / custom_func / multi_select_custom_func / date_custom_func
Description: The type of the filter to be used in the column
* custom_func
Required: true (when filter_type is custom_func / multi_select_custom_func / date_custom_func)
Type: function
Default value: undefined
Description: should be pointing to a function with the following signature myCustomFilterFunction(filterVal, columnVal, rowValues, stateVal) , where `filterVal` is the value from the select box,
`columnVal` is the value from the relevant row column, `rowValues` is an array that holds the values of the entire row and `stateVal` which holds the current state of the table row DOM
, stateVal is perfect to handle situations in which you placing radiobuttons / checkbox inside table column. This function should return true if the row matches your condition and the row should be displayed) and false otherwise
Note: When using multi_select_custom_func as filter_type filterVal will hold an array of selected values from the multi select element
* data
Required: false
Type: Array (of string or objects)
Description: When the need of predefined data for filter is needed just use an array of strings ["value1","value2"....] (supported in select / multi_select / auto_complete filters) or
array of objects [{value: 'Some Data 1', label: 'One'}, {value: 'Some Data 3', label: 'Three'}] (supported in select / multi_select filters)
Note: that when filter_type is custom_func / multi_select_custom_func this array will populate the custom filter select element
* data_as_is
Required: false
Type: boolean
Default value: false
Description: When set to true, the value of the data attribute will be fed into the filter as is (without any modification/decoration).
Perfect to use when you want to define your own <option></option> for the filter
Note: Currently supported by the select / multi_select filters
* append_data_to_table_data
Required: false
Type: String
Default value: undefined
Possible values: before / sorted
Description: Use 'before' to place your data array before the values that yadcf grabs from the table
use 'sorted' to place the data array sorted along with the values that yadcf grabs from the table
Note: 'sorted' option will have affect only if you data is an array of primitives (not objects)
* column_data_type
Required: false
Type: String
Default value: 'text'
Possible values: text / html / rendered_html / html5_data_complex
Description: The type of data in column , use "html" when you have some html code in the column (support parsing of multiple elements per cell),
use rendered_html when you are using render function of columnDefs or similar, that produces a html code, note that both types rendered_html and html have a fallback for simple text parsing.
html5_data_complex allows to populate filter with pairs of display/value by using datatables datatables HTML5 data-* attributes - should be used along with specifying html5_data attribute (read docs)
* column_data_render
Required: false
Type: function
Possible values: function (data) {return data.someValue || ('whatever ' + data.otherValue)}
Description: function that will help yadcf to know what is "text" is present in the cell
Note: Originally added to enable cumulative_filtering with column_data_type: "rendered_html"
* text_data_delimiter
Required: false
Type: String
Description: Delimiter that separates text in table column, for example text_data_delimiter: ","
* custom_range_delimiter:
Required: false
Type: String
Default value: '-yadcf_delim-'
Description: Delimiter that separates min and max values for number range filter type, for example custom_range_delimiter: 'minMax'
* html_data_type
Required: false
Type: String
Default value: 'text'
Possible values: text / value / id / selector
Description: When using "html" for column_data_type argument you can choose how exactly to parse your html element/s in column , for example use "text" for the following <span class="someClass">Some text</span>
Special notes: when using selector you must provide a valid selector string for the html_data_selector property
* html_data_selector
Required: false
Type: String
Default value: undefined
Possible values: any valid selector string, for example 'li:eq(1)'
Description: allows for advanced text value selection within the html located in the td element
Special notes: know that the selector string "begin is search" from (and not outside) the first element of the html inside the td
(supported by range_number_slider / select / auto_complete)
* html5_data
Required: false
Type: String
Default value: undefined
Possible values: data-filter / data-search / anything that is supported by datatables
Description: Allows to filter based on data-filter / data-search attributes of the <td> element, read more: http://www.datatables.net/examples/advanced_init/html5-data-attributes.html
Special notes: Can be used along with column_data_type: 'html5_data_complex' to populate filter with pairs of display/value instead of values only
* filter_container_id
Required: false
Type: String
Description: In case that user don't want to place the filter in column header , he can pass an id of the desired container for the column filter
* filter_container_selector
Required: false
Type: String
Description: In case that user don't want to place the filter in column header , he can pass a (jquery) selector of the desired container for the column filter
* filter_default_label
Required: false
Type: String / Array of string in case of range_number filter (first entry is for the first input and the second entry is for the second input
Default value: 'Select value'
Description: The label that will appear in the select menu filter when no value is selected from the filter
* omit_default_label
Required: false
Type: boolean
Default value: false
Description: Prevent yadcf from adding "default_label" (Select value / Select values)
Note Currently supported in select / multi_select / custom_func / multi_select_custom_func
* filter_reset_button_text
Required: false
Type: String / boolean
Default value: 'x'
Description: The text that will appear inside the reset button next to the select drop down (set this to false (boolean) in order to hide it from that column filter)
* enable_auto_complete (this attribute is deprecated , and will become obsolete in the future , so you better start using filter_type: "auto_complete")
Required: false
Type: boolean
Default value: false
Description: Turns the filter into an autocomplete input - make use of the jQuery UI Autocomplete widget (with some enhancements)
* sort_as
Required: false
Type: String
Default value: 'alpha'
Possible values: alpha / num / alphaNum / custom / none
Description: Defines how the values in the filter will be sorted, alphabetically / numerically / alphanumeric / custom / not sorted at all (none is useful to preserve
the order of the data attribute as is)
Note: When custom value is set you must provide a custom sorting function for the sort_as_custom_func property
* sort_as_custom_func
Required: false
Type: function
Default value: undefined
Description: Allows to provide a custom sorting function for the filter elements
* sort_order
Required: false
Type: String
Default value: 'asc'
Possible values: asc / desc
Description: Defines the order in which the values in the filter will be sorted, ascending or descending
* date_format
Required: false
Type: String
Default value: 'mm/dd/yyyy'
Possible values: mm/dd/yyyy / dd/mm/yyyy / hh:mm (when using datepicker_type: 'bootstrap-datetimepicker')
Description: Defines the format in which the date values are being parsed into Date object
Note: You can replace the / separator with other one , for example mm-dd-yy
* moment_date_format
Required: false
Type: String
Default value: undefined
Possible values: Any format accepted by momentjs
Description: Defines the format in which the table date values are being parsed into Date object by momentjs library
Note: Currently relevant only when using datepicker_type: 'bootstrap-datetimepicker')
* ignore_char
Required: false
Type: String
Description: Tells the range_number and range_number_slider to ignore specific char while filtering (that char can used as number separator)
Note: Use double escape for regex chars , e.g \\$ , also you can use multiple ignore chars with | , e.g '_|\\.|\\$'
* filter_match_mode
Required: false
Type: String
Default value: contains
Possible values: contains / exact / startsWith / regex
Description: Allows to control the matching mode of the filter (supported in select / auto_complete / text filters)
* exclude
Required: false
Type: boolean
Default value: undefined
Description: Adds a checkbox next to the filter that allows to do a "not/exclude" filtering (acts the same all filter_match_mode)
Note: Currently available for the text, select and number_range filter
* exclude_label
Required: false
Type: String
Default value: 'exclude'
Description: The label that will appear above the exclude checkbox
* regex_check_box
Required: false
Type: boolean
Default value: undefined
Description: Adds a checkbox next to the filter that allows to switch to regex filter_match_mode filtering on a fly
Note: Currently available for the text filter
* regex_label
Required: false
Type: String
Default value: 'regex'
Description: The label that will appear above the regex checkbox
* null_check_box
Required: false
Type: boolean
Default value: undefined
Description: Adds a checkbox next to the filter that allows to filter by null value,
works only for tables with data retrieved via data property, not working for html defined tables,
where null is represented as string
Note: Currently available for the text and range_number filters
* null_label
Required: false
Type: String
Default value: 'null'
Description: The label that will appear above the null checkbox
* checkbox_position_after
Required: false
Type: boolean
Default value: false
Description: Adds checkboxes exclude and regex after input text column
Note: Currently available for the text filter
* select_type
Required: false
Type: String
Default value: undefined
Possible values: chosen / select2 / custom_select
Description: Turns the simple select element into Chosen / Select2 (make use of the Chosen / Select2 select jQuery plugins)
Note: When using custom_select , make sure to call the initSelectPluginCustomTriggers,
before calling yadcf constructor / init function
* select_type_options
Required: false
Type: Object
Default value: {}
Description: This parameter will be passed "as is" to the Chosen/Select2 plugin constructor
* select_null_option
Required: false
Type: string
Default value: 'null'
Description: String value which internally represents null option in select filters,
also it is send to server if serverside feature is enabled
Supports exclude, with exclude enabled the string is wrapped with exclude regex
* filter_plugin_options
Required: false
Type: Object
Default value: undefined
Description: This parameter will be passed to the jQuery Autocomplete / jQuery Slider / Bootstrap Datetimepicker
* case_insensitive
Required: false
Type: boolean
Default value: true
Description: Do case-insensitive filtering (supported in select / auto_complete / text filters)
* filter_delay
Required: false
Type: integer
Default value: undefined
Description: Delay filter execution for a XXX milliseconds - filter will fire XXX milliseconds after the last keyup.
Special notes: Currently supported in text / range_number / range_date filters / range_number_slider
* datepicker_type
Required: false
Type: String
Default value: 'jquery-ui'
Possible values: 'jquery-ui' / 'bootstrap-datetimepicker' / bootstrap-datepicker / daterangepicker / dt-datetime (DataTable Editor DateTime picker)
Description: You can choose datapicker library from defined in special notes
Special notes: Currently supported only jQueryUI datepicker (datepicker) and Bootstrap datepicker (eonasdan-bootstrap-datetimepicker)
Bootstrap datepicker depends moment library. This plugin depends moment too.
* style_class
Required: false
Type: String
Description: Allows adding additional class/classes to filter - available for the following filters:
select / multi_select / text / custom_func / multi_select_custom_func / range_number / range_number_slider / range_date
* reset_button_style_class
Required: false
Type: String
Description: Allows adding additional class/classes to filter reset button
* externally_triggered_checkboxes_text
Required: false
Default value: false,
Type: boolean | string
Description: Adds external checkboxes button, and hides exclude/null/regex checkboxes
usecase: hide/show options (checkboxes) button, checkboxes in popover/modal
* externally_triggered_checkboxes_function
Required: false
Default value: undefined,
Type: function
Description: Adds onclick function to external checkboxes button, with event parameter
* externally_triggered_checkboxes_button_style_class
Required: false
Default value: ''
Type: String
Description: Allows adding additional class/classes to external checkboxes button
* Global Parameters (per table rather than per column)
*
* Usage example yadcf.init(oTable,[{column_number : 0}, {column_number: 3}],{cumulative_filtering: true});
* -------------
* externally_triggered
Required: false
Type: boolean
Default value: false
Description: Filters will filter only when yadcf.exFilterExternallyTriggered(table_arg) is called
Special notes: Useful when you want to build some form with filters and you want to trigger the filter when that form
"submit" button is clicked (instead of filtering per filter input change)
* cumulative_filtering
Required: false
Type: boolean
Default value: false
Description: Change the default behavior of the filters so its options will be populated from the filtered rows (remaining
table data after filtering) only, unlike the normal behavior in which the options of the filters are from all the table data
* filters_position
Required: false
Type: String
Default value: header
Possible values: 'header' / 'footer'
Description: Filters can be placed in the header (thead) or in the footer (tfoot) of the table,
Note: When 'footer' you must provide a valid tfoot element in your table
* filters_tr_index
Required: false
Type: integer
Default value: undefined
Description: Allow to control the index of the <tr> inside the thead of the table, e.g when one <tr> is used for headers/sort and
another <tr> is used for filters
* onInitComplete
Required: false
Type: function
Default value: undefined
Description: Calls the provided callback function in the end of the yadcf init function
Note: This callback function will run before datatables fires its event such as draw/xhr/etc., might be useful for call some
third parties init / loading code
* jquery_ui_datepicker_locale
Required: false
Type: string
Default value: ""
Description: Load localized jquery-ui datepicker
Note: Need to load jquery-ui-i18n lib.
Possible values: af, ar-DZ, ar, az, be, bg, bs, ca, cs, cy-GB, da, de, el, en-AU, en-GB, en-NZ, eo, es, et, eu, fa, fi, fo, fr-CA, fr-CH,
fr, gl, he, hi, hr, hu, hy, id, is, it-CH, it, ja, ka, kk, km, ko, ky, lb, lt, lv, mk, ml, ms, nb, nl-BE, nl, nn, no, pl,
pt-BR, pt, rm, ro, ru, sk, sl, sq, sr-SR, sr, sv, ta, th, tj, tr, uk, vi, zh-CN, zh-HK, zh-TW
* null_api_call_value
Required: false
Type: string
Default value: "null"
Description: Value which represents null, and is used as argument for fnFilter function, and sent to server
Note: works with null filter enabled only
* not_null_api_call_value
Required: false
Type: string
Default value: "!^@"
Description: Value which represents not null, and is used as argument for fnFilter function, and sent to server
Note: works with null filter enabled only
*
*
*
*
* External API functions:
*
*
* -------------
* exFilterColumn
Description: Allows to trigger filter/s externally/programmatically (support ALL filter types!!!) , perfect for showing table with pre filtered columns
Arguments: table_arg: (variable of the datatable),
array of pairs: column number String/Object with from and to, filter_value (the actual string value that we want to filter by)
Usage example: yadcf.exFilterColumn(oTable, [[0, 'Some Data 2']]); //pre filter one column
yadcf.exFilterColumn(oTable, [[0, 'Some Data 1'], [1, {from: 111, to: 1110}], [2, {from: "", to: "11/25/2014"}]]); //pre filter several columns
yadcf.exFilterColumn(oTable, [[0, ['Some Data 1','Some Data 2']]]); // for pre filtering multi select filter you should use array with values (or an array with single value)
* exGetColumnFilterVal
Description: Allows to retrieve column current filtered value (support ALL filter types!!!)
Arguments: table_arg: (variable of the datatable),
column number: column number from which we want the value
Usage example: yadcf.exGetColumnFilterVal(oTable,1);
Return value: String (for simple filter) / Object (for range filter) with from and to properties / Array of strings for multi_select filter
* exResetAllFilters
Description: Allows to reset all filters externally/programmatically (support ALL filter types!!!) , perfect for adding a "reset all" button to your page!
Arguments: table_arg: (variable of the datatable)
noRedraw: (boolean) , use it if you don't want your table to be reloaded after the filter reset,
for example if you planning to call exFilterColumn function right after the exResetAllFilters (to avoid two AJAX requests)
Usage example: yadcf.exResetAllFilters(oTable);
* exResetFilters
Description: Allows to reset specific filters externally/programmatically (support ALL filter types!!!) , can be used for resetting one or more filters
Arguments: table_arg: (variable of the datatable)
array with columns numbers
noRedraw: (boolean) , use it if you don't want your table to be reloaded after the filter reset,
for example if you planning to call exFilterColumn function right after the exResetFilters (to avoid two AJAX requests)
Usage example: yadcf.exResetFilters(oTable, [1,2]);
* initSelectPluginCustomTriggers
Description: Allows to set any select jquery plugin initialize and refresh functions. jQuery selector will be passed to the user defined function to initialize and refresh the plugin.
Great for integrating any jquery select plugin (Selectize / MultiSelect / etc)
Arguments: initFunc : function which will initialize the plugin
refreshFunc : function that will refresh the plugin.
destroyFunc : function that will destroy the plugin (upon table destroy even trigger).
Usage example: yadcf.initSelectPluginCustomTriggers(function ($filterSelector){$filterSelector.multiselect({});}, function ($filterSelector){$filterSelector.multiselect("refresh")}, , function ($filterSelector){$filterSelector.multiselect("destroy")});
* exFilterExternallyTriggered
Description: Triggers all the available filters, should be used only when the externally_triggered option used
Arguments: table_arg: (variable of the datatable)
Usage example: yadcf.exFilterExternallyTriggered(table_arg);
* exRefreshColumnFilterWithDataProp
Description: Updates column filter with new data, when data property was used in initialization for this filter
e.g. select filter, when we used data property and we want to update it
Arguments: table_arg: variable of the datatable
col_num: number index of column filter
updatedData: array of new data (use same data structure as was used in yadcf.init options)
Usage example: yadcf.exRefreshColumnFilterWithDataProp(table_arg, 5, ['One', 'Two', 'Three']);
* initOnDtXhrComplete
Description: Allows to set a callback function to be called after dt xhr finishes
Arguments: function to do some logic
Usage example: yadcf.initOnDtXhrComplete(function() { $("#yadcf-filter--example-0").multiselect('refresh'); });
* initDefaults
Description: Init global defaults for all yadcf instances.
Arguments: Object consisting of anything defined inside default_options variable
Usage example: yadcf.initDefaults({language: {select: 'Pick some'}});
*
*
*
* Server-side processing API (see more on showcase):
*
* From server to client:
* In order to populate the filters with data from server (select / auto_complete / range_number_slider (min and max values), you should add to your current json respond the following properties:
* lets say for first column you add yadcf_data_0 filled with array of values, for column second column yadcf_data_1 and so on...
*
* From client to server:
* Read the filtered value like this (for first column) req.getParameter("columns[0][search][value]"); <- java code , php/.Net/etc you just need to get it from the request
* Range filter value will arrive delimited by -yadcf_delim- , so just split it into an array or something like this: String[] minMax = sSearch_0.split("-yadcf_delim-");
*
*
*
*
*
* Working with filters for multiple tables:
*
*
* -------------
* initMultipleTables
Description: Allows to create filter that will affect multiple tables / multiple column(s) in multiple tables
Arguments: Array of tables,
Array of objects with properties for each filter
Usage example: yadcf.initMultipleTables([oTable, oTable2], [{
column_number: [0, 1], filter_container_id: 'multi-table-filter-0', filter_default_label: 'Filter all tables columns 1 and 2!'
},
{
column_number: [2], filter_container_id: 'multi-table-filter-1', filter_default_label: 'Filter all tables column 3!'
}]);
Valid properties: filter_type: 'text' (default) / 'select' / 'multi_select',
column_number: not required (in that case the filter will be global)
can be either number(single column filter) or array of numbers(multiple columns filter)
filter_container_id: '' (required),
Note: All the usual properties of yadcf should be supported in initMultipleTables too!
* initMultipleColumns
Description: Allows to create filter that will affect multiple column(s) in in a particular table
Arguments: Table variable,
Array of objects with properties for each filter
Usage example: yadcf.initMultipleColumns(oTable, [{
column_number: [0, 1], filter_container_id: 'multi-table-filter-0', filter_default_label: 'Filter columns 1 and 2!'
},
{
column_number: [2, 3], filter_container_id: 'multi-table-filter-1', filter_default_label: 'Filter column 3 and 4!'
}]);
Valid properties: filter_type: 'text' (default) / 'select' / 'multi_select',
column_number: not required (in that case the filter will be global)
can be either number(single column filter) or array of numbers(multiple columns filter)
filter_container_id: '' (required),
Note: All the usual properties of yadcf should be supported in initMultipleColumns too!
*/
//Polyfills
if (window.NodeList && !NodeList.prototype.forEach) {
NodeList.prototype.forEach = function (callback, thisArg) {
thisArg = thisArg || window;
for (var i = 0; i < this.length; i++) {
callback.call(thisArg, this[i], i, this);
}
};
}
if (!Object.entries) {
Object.entries = function (obj) {
var ownProps = Object.keys(obj),
i = ownProps.length,
resArray = new Array(i); // preallocate the Array
while (i--)
resArray[i] = [ownProps[i], obj[ownProps[i]]];
return resArray;
};
}
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], function ($) {
return factory($, window, document);
});
} else if (typeof module === 'object') {
// CommonJS
module.exports = function (root, $) {
if (!root) {
// CommonJS environments without a window global must pass a
// root. This will give an error otherwise
root = window;
}
if (!$) {
$ = typeof window !== 'undefined' ? // jQuery's factory checks for a global window
require('jquery') :
require('jquery')(root);
}
return factory($, root, root.document);
};
} else {
// Browser
factory(jQuery, window, document);
}
}
(function ($, window, document, undefined) {
var yadcf = (function () {
'use strict';
var tablesDT = {},
oTables = {},
oTablesIndex = {},
options = {},
plugins = {},
exFilterColumnQueue = [],
yadcfDelay,
selectElementCustomInitFunc,
selectElementCustomRefreshFunc,
selectElementCustomDestroyFunc,
default_options = {
filter_type: "select",
enable_auto_complete: false,
sort_as: "alpha",
sort_order: "asc",
date_format: "mm/dd/yyyy",
ignore_char: undefined,
filter_match_mode: "contains",
select_type: undefined,
select_type_options: {},
select_null_option: 'null',
case_insensitive: true,
column_data_type: 'text',
html_data_type: 'text',
exclude_label: 'exclude',
regex_label: 'regex',
null_label: 'null',
checkbox_position_after: false,
style_class: '',
reset_button_style_class: '',
datepicker_type: 'jquery-ui',
range_data_type: 'single',
range_data_type_delim: '-',
omit_default_label: false,
custom_range_delimiter: '-yadcf_delim-',
externally_triggered_checkboxes_text: false,
externally_triggered_checkboxes_function: undefined,
externally_triggered_checkboxes_button_style_class: '',
language: {
select: 'Select value',
select_multi: 'Select values',
filter: 'Type to filter',
range: ['From', 'To'],
date: 'Select a date'
}
},
settingsMap = {},
dTXhrComplete;
let ctrlPressed = false;
let closeBootstrapDatepicker = false;
let closeBootstrapDatepickerRange = false;
let closeSelect2 = false;
//From ColReorder (SpryMedia Ltd (www.sprymedia.co.uk))
function getSettingsObjFromTable(dt) {
var oDTSettings;
if ($.fn.dataTable.Api) {
oDTSettings = new $.fn.dataTable.Api(dt).settings()[0];
} else if (dt.fnSettings) { // 1.9 compatibility
// DataTables object, convert to the settings object
oDTSettings = dt.fnSettings();
} else if (typeof dt === 'string') { // jQuery selector
if ($.fn.dataTable.fnIsDataTable($(dt)[0])) {
oDTSettings = $(dt).eq(0).dataTable().fnSettings();
}
} else if (dt.nodeName && dt.nodeName.toLowerCase() === 'table') {
// Table node
if ($.fn.dataTable.fnIsDataTable(dt.nodeName)) {
oDTSettings = $(dt.nodeName).dataTable().fnSettings();
}
} else if (dt instanceof jQuery) {
// jQuery object
if ($.fn.dataTable.fnIsDataTable(dt[0])) {
oDTSettings = dt.eq(0).dataTable().fnSettings();
}
} else {
// DataTables settings object
oDTSettings = dt;
}
return oDTSettings;
}
function arraySwapValueWithIndex(pArray) {
var tmp = [],
i;
for (i = 0; i < pArray.length; i++) {
tmp[pArray[i]] = i;
}
return tmp;
}
function arraySwapValueWithIndex2(pArray) {
var tmp = [],
i;
for (i = 0; i < pArray.length; i++) {
tmp[pArray[i]._ColReorder_iOrigCol] = i;
}
return tmp;
}
function initColReorder2(settingsDt, table_selector_jq_friendly) {
if (settingsDt.oSavedState && settingsDt.oSavedState.ColReorder !== undefined) {
if (plugins[table_selector_jq_friendly] === undefined) {
plugins[table_selector_jq_friendly] = {};
plugins[table_selector_jq_friendly].ColReorder = arraySwapValueWithIndex(settingsDt.oSavedState.ColReorder);
}
} else if (settingsDt.aoColumns[0]._ColReorder_iOrigCol !== undefined) {
if (plugins[table_selector_jq_friendly] === undefined) {
plugins[table_selector_jq_friendly] = {};
plugins[table_selector_jq_friendly].ColReorder = arraySwapValueWithIndex2(settingsDt.aoColumns);
}
}
}
function initColReorderFromEvent(table_selector_jq_friendly) {
plugins[table_selector_jq_friendly] = undefined;
}
function columnsArrayToString(column_number) {
var column_number_obj = {};
if (column_number !== undefined) {
if (column_number instanceof Array) {
column_number_obj.column_number_str = column_number.join('_');
} else {
column_number_obj.column_number_str = column_number;
column_number = [];
column_number.push(column_number_obj.column_number_str);
}
} else {
column_number_obj.column_number_str = 'global';
}
column_number_obj.column_number = column_number;
return column_number_obj;
}
function initDefaults(params) {
return $.extend(true, default_options, params);
}
function getOptions(selector) {
return options[selector];
}
function getAllOptions() {
return options;
}
function eventTargetFixUp(pEvent) {
if (pEvent.target === undefined) {
pEvent.target = pEvent.srcElement;
}
return pEvent;
}
function dot2obj(tmpObj, dot_refs) {
var i = 0;
dot_refs = dot_refs.split(".");
for (i = 0; i < dot_refs.length; i++) {
if (tmpObj[dot_refs[i]] !== undefined && tmpObj[dot_refs[i]] !== null) {
tmpObj = tmpObj[dot_refs[i]];
} else {
return '';
}
}
return tmpObj;
}
function setOptions(selector_arg, options_arg, params, table) {
var tmpOptions = {},
i,
col_num_as_int;
//adaptContainerCssClassImpl = function (dummy) { return ''; };
$.extend(true, default_options, params);
if (options_arg.length === undefined) {
options[selector_arg] = options_arg;
return;
}
for (i = 0; i < options_arg.length; i++) {
if (options_arg[i].date_format !== undefined && options_arg[i].moment_date_format === undefined) {
options_arg[i].moment_date_format = options_arg[i].date_format;
}
if (options_arg[i].select_type === 'select2') {
default_options.select_type_options = {
//adaptContainerCssClass: adaptContainerCssClassImpl
};
}
//no individual reset button for externally_triggered mode
if (default_options.externally_triggered === true) {
options_arg[i].filter_reset_button_text = false;
}
//validate custom function required attributes
if (options_arg[i].filter_type !== undefined && options_arg[i].filter_type.indexOf('custom_func') !== -1) {
if (options_arg[i].custom_func === undefined) {
console.log('Error: You are trying to use filter_type: "custom_func / multi_select_custom_func" for column ' + options_arg[i].column_number + ' but there is no such custom_func attribute provided (custom_func: \"function reference goes here...\")');
return;
}
}
if (!options_arg[i].column_selector) {
col_num_as_int = +options_arg[i].column_number;
if (isNaN(col_num_as_int)) {
tmpOptions[options_arg[i].column_number_str] = $.extend(true, {}, default_options, options_arg[i]);
} else {
tmpOptions[col_num_as_int] = $.extend(true, {}, default_options, options_arg[i]);
}
} else {
if (table && table.column) {
//translate from column_selector to column_number
let columnNumber = table.column(options_arg[i].column_selector);
if (columnNumber.index() >= 0) {
options_arg[i].column_number = columnNumber.index();
tmpOptions[options_arg[i].column_number] = $.extend(true, {}, default_options, options_arg[i]);
}
}
}
}
options[selector_arg] = tmpOptions;
check3rdPPluginsNeededClose();
}
function check3rdPPluginsNeededClose() {
Object.entries(getAllOptions()).forEach(function (tableEntry) {
Object.entries(tableEntry[1]).forEach(function (columnEntry) {
if (columnEntry[1].datepicker_type === 'bootstrap-datepicker') {
if (columnEntry[1].filter_type === 'range_date') {
closeBootstrapDatepickerRange = true;
} else {
closeBootstrapDatepicker = true;
}
} else if (columnEntry[1].select_type === 'select2') {
closeSelect2 = true;
}
});
});
}
//taken and modified from DataTables 1.10.0-beta.2 source
function yadcfVersionCheck(version) {
var aThis = $.fn.dataTable.ext.sVersion.split('.'),
aThat = version.split('.'),
iThis,
iThat,
i,
iLen;
for (i = 0, iLen = aThat.length; i < iLen; i++) {
iThis = parseInt(aThis[i], 10) || 0;
iThat = parseInt(aThat[i], 10) || 0;
// Parts are the same, keep comparing
if (iThis === iThat) {
continue;
}
// Parts are different, return immediately
return iThis > iThat;
}
return true;
}
function resetIApiIndex() {
$.fn.dataTableExt.iApiIndex = 0;
}
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|'\[\]\/\\])/g, "\\$1");
}
function escapeRegExpInArray(arr) {
var i;
for (i = 0; i < arr.length; i++) {
arr[i] = arr[i].replace(/([.*+?^=!:${}()|'\[\]\/\\])/g, "\\$1");
}
return arr;
}
function replaceAll(string, find, replace) {
return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function getTableId(obj) {
var tableId;
if (obj.table !== undefined) {
tableId = obj.table().node().id;
} else {
tableId = getSettingsObjFromTable(obj).sTableId;
}
return tableId;
}
function generateTableSelectorJQFriendly2(obj) {
var tmpStr;
if (obj.oInstance !== undefined && obj.oInstance.selector !== undefined) {
tmpStr = obj.oInstance.selector;
} else if (obj.selector !== undefined) {
tmpStr = obj.selector;
} else if (obj.table !== undefined) {
tmpStr = obj.table().node().id;
} else {
return '';
}
tmpStr = replaceAll(tmpStr, ".", "-");
tmpStr = replaceAll(tmpStr, ' ', '');
return tmpStr.replace(":", "-").replace("(", "").replace(")", "").replace("#", "-");
}
function generateTableSelectorJQFriendlyNew(tmpStr) {
tmpStr = replaceAll(tmpStr, ":", "-");
tmpStr = replaceAll(tmpStr, "(", "");
tmpStr = replaceAll(tmpStr, ")", "");
tmpStr = replaceAll(tmpStr, ",", "");
tmpStr = replaceAll(tmpStr, ".", "-");
tmpStr = replaceAll(tmpStr, "#", "-");
tmpStr = replaceAll(tmpStr, ' ', '');
return tmpStr;
}
yadcfDelay = (function () {
var timer = 0;
return function (callback, ms, param) {
clearTimeout(timer);
timer = setTimeout(function () {
callback(param);
}, ms);
return timer;
};
}());
function initializeSelectPlugin(selectType, $selectObject, select_type_options) {
if (selectType === 'chosen') {
$selectObject.chosen(select_type_options);
$selectObject.next().on("click", yadcf.stopPropagation).on("mousedown", yadcf.stopPropagation);
refreshSelectPlugin({
select_type: selectType,
select_type_options: select_type_options
}, $selectObject);
} else if (selectType === 'select2') {
if (!$selectObject.data('select2')) {
$selectObject.select2(select_type_options);
}
if ($selectObject.next().hasClass('select2-container')) {
$selectObject.next().on("click", yadcf.stopPropagation).on("mousedown", yadcf.stopPropagation);
}
} else if (selectType === 'custom_select') {
selectElementCustomInitFunc($selectObject);
$selectObject.next().on("click", yadcf.stopPropagation).on("mousedown", yadcf.stopPropagation);
}
}
function refreshSelectPlugin(columnObj, $selectObject, val) {
var selectType = columnObj.select_type,
select_type_options = columnObj.select_type_options;
if (selectType === 'chosen') {
$selectObject.trigger("chosen:updated");
} else if (selectType === 'select2') {
if (!$selectObject.data('select2')) {
$selectObject.select2(select_type_options);
}
if (val !== undefined) {
$selectObject.val(val);
}
$selectObject.trigger('change');
} else if (selectType === 'custom_select') {
selectElementCustomRefreshFunc($selectObject);
}
}
function initSelectPluginCustomTriggers(initFunc, refreshFunc, destroyFunc) {
selectElementCustomInitFunc = initFunc;
selectElementCustomRefreshFunc = refreshFunc;
selectElementCustomDestroyFunc = destroyFunc;
}
function initOnDtXhrComplete(initFunc) {
dTXhrComplete = initFunc;
}
//Used by exFilterColumn for translating readable search value into proper search string for datatables filtering
function yadcfMatchFilterString(table_arg, column_number, selected_value, filter_match_mode, multiple, exclude) {
var case_insensitive = yadcf.getOptions(table_arg.selector)[column_number].case_insensitive,
ret_val;
if (!selected_value) {
return '';
}
table_arg.fnSettings().aoPreSearchCols[column_number].bSmart = false;
table_arg.fnSettings().aoPreSearchCols[column_number].bRegex = true;
table_arg.fnSettings().aoPreSearchCols[column_number].bCaseInsensitive = case_insensitive;
if (multiple === undefined || multiple === false) {
if (exclude !== true) {
if (filter_match_mode === "contains") {
table_arg.fnSettings().aoPreSearchCols[column_number].bSmart = true;
table_arg.fnSettings().aoPreSearchCols[column_number].bRegex = false;
ret_val = selected_value;
} else if (filter_match_mode === "exact") {
ret_val = "^" + selected_value + "$";
} else if (filter_match_mode === "startsWith") {
ret_val = "^" + selected_value;
} else if (filter_match_mode === "regex") {
ret_val = selected_value;
}
} else {
ret_val = "^((?!" + selected_value + ").)*$";
}
} else {
if (filter_match_mode !== 'regex') {
if (!(selected_value instanceof Array)) {
selected_value = [selected_value];
}
selected_value = escapeRegExpInArray(selected_value);
}
if (filter_match_mode === "contains") {
ret_val = selected_value.join("|");
} else if (filter_match_mode === "exact") {
ret_val = "^(" + selected_value.join("|") + ")$";
} else if (filter_match_mode === "startsWith") {
ret_val = "^(" + selected_value.join("|") + ")";
} else if (filter_match_mode === "regex") {
ret_val = selected_value;
}
}
return ret_val;
}
function yadcfMatchFilter(oTable, selected_value, filter_match_mode, column_number, exclude, original_column_number) {
var columnObj = getOptions(oTable.selector)[original_column_number],
case_insensitive = columnObj.case_insensitive;
if (exclude !== true) {
if (filter_match_mode === "contains") {
oTable.fnFilter(selected_value, column_number, false, false, true, case_insensitive);
} else if (filter_match_mode === "exact") {
let prefix = '^';
let suffix = '$';
if (columnObj.text_data_delimiter !== undefined) {
let text_data_delimiter = escapeRegExp(columnObj.text_data_delimiter);
prefix = '(' + prefix + '|' + text_data_delimiter + ')';
suffix = '(' + suffix + '|' + text_data_delimiter + ')';
}
selected_value = escapeRegExp(selected_value);
oTable.fnFilter(prefix + selected_value + suffix, column_number, true, false, true, case_insensitive);
} else if (filter_match_mode === "startsWith") {
selected_value = escapeRegExp(selected_value);
oTable.fnFilter("^" + selected_value, column_number, true, false, true, case_insensitive);
} else if (filter_match_mode === "regex") {
try {
//validate regex, only call fnFilter if valid
new RegExp(selected_value);
} catch (error) {
return;
}
oTable.fnFilter(selected_value, column_number, true, false, true, case_insensitive);
}
} else {
if (filter_match_mode === "exact") {
selected_value = "^" + escapeRegExp(selected_value) + "$";
} else if (filter_match_mode === "startsWith") {
selected_value = "^" + escapeRegExp(selected_value);
}
oTable.fnFilter("^((?!" + selected_value + ").)*$", column_number, true, false, true, case_insensitive);
}
}
function yadcfParseMatchFilter(tmpStr, filter_match_mode) {
var retVal;
if (filter_match_mode === "contains") {
retVal = tmpStr;
} else if (filter_match_mode === "exact") {
retVal = tmpStr.substring(1, tmpStr.l