1 // These default options are for translation but can be used
2 // for any other datatables settings
4 // $("#table_id").dataTable($.extend(true, {}, dataTableDefaults, {
7 var dataTablesDefaults = {
10 "first" : window.MSG_DT_FIRST || "First",
11 "last" : window.MSG_DT_LAST || "Last",
12 "next" : window.MSG_DT_NEXT || "Next",
13 "previous" : window.MSG_DT_PREVIOUS || "Previous"
15 "emptyTable" : window.MSG_DT_EMPTY_TABLE || "No data available in table",
16 "info" : window.MSG_DT_INFO || "Showing _START_ to _END_ of _TOTAL_ entries",
17 "infoEmpty" : window.MSG_DT_INFO_EMPTY || "No entries to show",
18 "infoFiltered" : window.MSG_DT_INFO_FILTERED || "(filtered from _MAX_ total entries)",
19 "lengthMenu" : window.MSG_DT_LENGTH_MENU || "Show _MENU_ entries",
20 "loadingRecords" : window.MSG_DT_LOADING_RECORDS || "Loading...",
21 "processing" : window.MSG_DT_PROCESSING || "Processing...",
22 "search" : window.MSG_DT_SEARCH || "Search:",
23 "zeroRecords" : window.MSG_DT_ZERO_RECORDS || "No matching records found",
25 "copyTitle" : window.MSG_DT_COPY_TO_CLIPBOARD || "Copy to clipboard",
26 "copyKeys" : window.MSG_DT_COPY_KEYS || "Press <i>ctrl</i> or <i>⌘</i> + <i>C</i> to copy the table data<br>to your system clipboard.<br><br>To cancel, click this message or press escape.",
28 _: window.MSG_DT_COPIED_ROWS || "Copied %d rows to clipboard",
29 1: window.MSG_DT_COPIED_ONE_ROW || "Copied one row to clipboard",
38 className: "dt_button_clear_filter",
39 titleAttr: window.MSG_CLEAR_FILTER,
41 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + window.MSG_CLEAR_FILTER + '</span>',
42 available: function ( dt ) {
43 // The "clear filter" button is made available if this test returns true
44 if( dt.settings()[0].aanFeatures.f ){ // aanFeatures.f is null if there is no search form
48 action: function ( e, dt, node ) {
49 dt.search( "" ).draw("page");
50 node.addClass("disabled");
53 initComplete: function( settings) {
54 var tableId = settings.nTable.id
55 // When the DataTables search function is triggered,
56 // enable or disable the "Clear filter" button based on
57 // the presence of a search string
58 $("#" + tableId ).on( 'search.dt', function ( e, settings ) {
59 if( settings.oPreviousSearch.sSearch == "" ){
60 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").addClass("disabled");
62 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").removeClass("disabled");
69 // Return an array of string containing the values of a particular column
70 $.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
71 // check that we have a column id
72 if ( typeof iColumn == "undefined" ) return new Array();
73 // by default we only wany unique data
74 if ( typeof bUnique == "undefined" ) bUnique = true;
75 // by default we do want to only look at filtered data
76 if ( typeof bFiltered == "undefined" ) bFiltered = true;
77 // by default we do not wany to include empty values
78 if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
79 // list of rows which we're going to loop through
81 // use only filtered rows
82 if (bFiltered == true) aiRows = oSettings.aiDisplay;
84 else aiRows = oSettings.aiDisplayMaster; // all row numbers
87 var asResultData = new Array();
88 for (var i=0,c=aiRows.length; i<c; i++) {
90 var aData = this.fnGetData(iRow);
91 var sValue = aData[iColumn];
92 // ignore empty values?
93 if (bIgnoreEmpty == true && sValue.length == 0) continue;
94 // ignore unique values?
95 else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
96 // else push the value onto the result data array
97 else asResultData.push(sValue);
102 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
103 // These keys must not launch filtering
104 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
106 // Set a filtering delay for global search field
107 jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
109 * Inputs: object:oSettings - dataTables settings object - automatically given
110 * integer:iDelay - delay in milliseconds
111 * Usage: $('#example').dataTable().fnSetFilteringDelay(250);
112 * Author: Zygimantas Berziunas (www.zygimantas.com) and Allan Jardine
113 * License: GPL v2 or BSD 3 point style
114 * Contact: zygimantas.berziunas /AT\ hotmail.com
118 iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay;
120 this.each( function ( i ) {
121 $.fn.dataTableExt.iApiIndex = i;
125 sPreviousSearch = null,
126 anControl = $( 'input', _that.fnSettings().aanFeatures.f );
128 anControl.unbind( 'keyup.DT' ).bind( 'keyup.DT', function(event) {
130 if (blacklist_keys.indexOf(event.keyCode) != -1) {
132 }else if ( event.keyCode == '13' ) {
133 $.fn.dataTableExt.iApiIndex = i;
134 _that.fnFilter( $(this).val() );
136 if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
137 window.clearTimeout(oTimerId);
138 sPreviousSearch = anControl.val();
139 oTimerId = window.setTimeout(function() {
140 $.fn.dataTableExt.iApiIndex = i;
141 _that.fnFilter( anControl.val() );
152 // Add a filtering delay on general search and on all input (with a class 'filter')
153 jQuery.fn.dataTableExt.oApi.fnAddFilters = function ( oSettings, sClass, iDelay ) {
155 this.fnSetFilteringDelay(iDelay);
156 var filterTimerId = null;
157 $(table).find("input."+sClass).keyup(function(event) {
158 if (blacklist_keys.indexOf(event.keyCode) != -1) {
160 }else if ( event.keyCode == '13' ) {
161 table.fnFilter( $(this).val(), $(this).attr('data-column_num') );
163 window.clearTimeout(filterTimerId);
165 filterTimerId = window.setTimeout(function() {
166 table.fnFilter($(input).val(), $(input).attr('data-column_num'));
170 $(table).find("select."+sClass).on('change', function() {
171 table.fnFilter($(this).val(), $(this).attr('data-column_num'));
175 // Sorting on html contains
176 // <a href="foo.pl">bar</a> sort on 'bar'
177 function dt_overwrite_html_sorting_localeCompare() {
178 jQuery.fn.dataTableExt.oSort['html-asc'] = function(a,b) {
179 a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
180 b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
181 if (typeof(a.localeCompare == "function")) {
182 return a.localeCompare(b);
184 return (a > b) ? 1 : ((a < b) ? -1 : 0);
188 jQuery.fn.dataTableExt.oSort['html-desc'] = function(a,b) {
189 a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
190 b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
191 if(typeof(b.localeCompare == "function")) {
192 return b.localeCompare(a);
194 return (b > a) ? 1 : ((b < a) ? -1 : 0);
198 jQuery.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
199 var x = a.replace( /<.*?>/g, "" );
200 var y = b.replace( /<.*?>/g, "" );
203 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
206 jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
207 var x = a.replace( /<.*?>/g, "" );
208 var y = b.replace( /<.*?>/g, "" );
211 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
215 $.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
216 var x = a.replace( /<.*?>/g, "" );
217 var y = b.replace( /<.*?>/g, "" );
220 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
223 $.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
224 var x = a.replace( /<.*?>/g, "" );
225 var y = b.replace( /<.*?>/g, "" );
228 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
234 * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
235 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
236 * Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
237 * See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
239 function naturalSort (a, b) {
240 var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
241 sre = /(^[ ]*|[ ]*$)/g,
242 dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
243 hre = /^0x[0-9a-f]+$/i,
245 // convert all to strings and trim()
246 x = a.toString().replace(sre, '') || '',
247 y = b.toString().replace(sre, '') || '',
249 xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
250 yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
251 // numeric, hex or date detection
252 xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
253 yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
254 // first try and sort Hex codes or Dates
256 if ( xD < yD ) return -1;
257 else if ( xD > yD ) return 1;
258 // natural sorting through split numeric strings and default strings
259 for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
260 // find floats not starting with '0', string or 0 if not defined (Clint Priest)
261 var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
262 var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
263 // handle numeric vs string comparison - number < string - (Kyle Adams)
264 if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
265 // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
266 else if (typeof oFxNcL !== typeof oFyNcL) {
270 if (oFxNcL < oFyNcL) return -1;
271 if (oFxNcL > oFyNcL) return 1;
276 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
277 "natural-asc": function ( a, b ) {
278 return naturalSort(a,b);
281 "natural-desc": function ( a, b ) {
282 return naturalSort(a,b) * -1;
288 /* Plugin to allow sorting on data stored in a span's title attribute
290 * Ex: <td><span title="[% ISO_date %]">[% formatted_date %]</span></td>
292 * In DataTables config:
294 * { "sType": "title-string" },
296 * http://datatables.net/plug-ins/sorting#hidden_title_string
298 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
299 "title-string-pre": function ( a ) {
300 var m = a.match(/title="(.*?)"/);
301 if ( null !== m && m.length ) {
302 return m[1].toLowerCase();
307 "title-string-asc": function ( a, b ) {
308 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
311 "title-string-desc": function ( a, b ) {
312 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
316 /* Plugin to allow sorting on numeric data stored in a span's title attribute
318 * Ex: <td><span title="[% decimal_number_that_JS_parseFloat_accepts %]">
319 * [% formatted currency %]
322 * In DataTables config:
324 * { "sType": "title-numeric" },
326 * http://datatables.net/plug-ins/sorting#hidden_title
328 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
329 "title-numeric-pre": function ( a ) {
330 var x = a.match(/title="*(-?[0-9\.]+)/)[1];
331 return parseFloat( x );
334 "title-numeric-asc": function ( a, b ) {
335 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
338 "title-numeric-desc": function ( a, b ) {
339 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
345 /* Plugin to allow text sorting to ignore articles
347 * In DataTables config:
349 * { "sType": "anti-the" },
351 * Based on the plugin found here:
352 * http://datatables.net/plug-ins/sorting#anti_the
353 * Modified to exclude HTML tags from sorting
354 * Extended to accept a string of space-separated articles
355 * from a configuration file (in English, "a," "an," and "the")
358 var config_exclude_articles_from_sort = window.CONFIG_EXCLUDE_ARTICLES_FROM_SORT || "a an the";
359 if (config_exclude_articles_from_sort){
360 var articles = config_exclude_articles_from_sort.split(" ");
362 for(i=0;i<articles.length;i++){
363 rpattern += "^" + articles[i] + " ";
364 if(i < articles.length - 1){ rpattern += "|"; }
366 var re = new RegExp(rpattern, "i");
369 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
370 "anti-the-pre": function ( a ) {
371 var x = String(a).replace( /<[\s\S]*?>/g, "" );
373 var z = y.replace(re, "").toLowerCase();
377 "anti-the-asc": function ( a, b ) {
378 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
381 "anti-the-desc": function ( a, b ) {
382 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
388 // Remove string between NSB NSB characters
389 $.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
390 var pattern = new RegExp("\x88.*\x89");
391 a = a.replace(pattern, "");
392 b = b.replace(pattern, "");
393 return (a > b) ? 1 : ((a < b) ? -1 : 0);
395 $.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
396 var pattern = new RegExp("\x88.*\x89");
397 a = a.replace(pattern, "");
398 b = b.replace(pattern, "");
399 return (b > a) ? 1 : ((b < a) ? -1 : 0);
402 /* Define two custom functions (asc and desc) for basket callnumber sorting */
403 jQuery.fn.dataTableExt.oSort['callnumbers-asc'] = function(x,y) {
404 var x_array = x.split("<div>");
405 var y_array = y.split("<div>");
407 /* Pop the first elements, they are empty strings */
411 x_array = jQuery.map( x_array, function( a ) {
412 return parse_callnumber( a );
414 y_array = jQuery.map( y_array, function( a ) {
415 return parse_callnumber( a );
424 if ( !x ) { x = ""; }
425 if ( !y ) { y = ""; }
427 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
430 jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
431 var x_array = x.split("<div>");
432 var y_array = y.split("<div>");
434 /* Pop the first elements, they are empty strings */
438 x_array = jQuery.map( x_array, function( a ) {
439 return parse_callnumber( a );
441 y_array = jQuery.map( y_array, function( a ) {
442 return parse_callnumber( a );
451 if ( !x ) { x = ""; }
452 if ( !y ) { y = ""; }
454 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
457 function parse_callnumber ( html ) {
458 var array = html.split('<span class="callnumber">');
460 array = array[1].split('</span>');
467 // see http://www.datatables.net/examples/advanced_init/footer_callback.html
468 function footer_column_sum( api, column_numbers ) {
469 // Remove the formatting to get integer data for summation
470 var intVal = function ( i ) {
471 if ( typeof i === 'number' ) {
472 if ( isNaN(i) ) return 0;
474 } else if ( typeof i === 'string' ) {
475 var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
476 if ( isNaN(value) ) return 0;
483 for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
484 var column_number = column_numbers[indice];
487 var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
488 $(cells).each(function(){
489 total += intVal( $(this).html() );
491 total /= 100; // Hard-coded decimal precision
494 $( api.column( column_number ).footer() ).html(total.format_price());
498 function filterDataTable( table, column, term ){
500 table.column( column ).search( term ).draw("page");
502 table.search( term ).draw("page");
506 jQuery.fn.dataTable.ext.errMode = function(settings, note, message) {
507 console.warn(message);
512 $.fn.api = function(options, columns_settings, add_filters) {
515 if(!options.criteria || ['contains', 'starts_with', 'ends_with', 'exact'].indexOf(options.criteria.toLowerCase()) === -1) options.criteria = 'contains';
516 options.criteria = options.criteria.toLowerCase();
517 settings = $.extend(true, {}, dataTablesDefaults, {
524 'emptyTable': (options.emptyTable) ? options.emptyTable : "No data available in table"
526 'pagingType': 'full',
531 'beforeSend': function(xhr, settings) {
534 xhr.setRequestHeader('x-koha-embed', Array.isArray(options.embed)?options.embed.join(','):options.embed);
536 if(options.header_filter && options.query_parameters) {
537 xhr.setRequestHeader('x-koha-query', options.query_parameters);
538 delete options.query_parameters;
541 'dataFilter': function(data, type) {
542 var json = {data: JSON.parse(data)};
543 if(total = this._xhr.getResponseHeader('x-total-count')) {
544 json.recordsTotal = total;
545 json.recordsFiltered = total;
547 return JSON.stringify(json);
549 'data': function( data, settings ) {
550 var length = data.length;
551 var start = data.start;
554 _page: Math.floor(start/length) + 1,
558 var filter = data.search.value;
559 var query_parameters = settings.aoColumns
560 .filter(function(col) {
561 return col.bSearchable && typeof col.data == 'string' && (data.columns[col.idx].search.value != '' || filter != '')
565 var value = data.columns[col.idx].search.value != '' ? data.columns[col.idx].search.value : filter;
566 part[!col.data.includes('.')?'me.'+col.data:col.data] = options.criteria === 'exact'?value:{like: (['contains', 'ends_with'].indexOf(options.criteria) !== -1?'%':'')+value+(['contains', 'starts_with'].indexOf(options.criteria) !== -1?'%':'')};
570 if(query_parameters.length) {
571 query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:query_parameters);
572 if(options.header_filter) {
573 options.query_parameters = query_parameters;
575 dataSet.q = query_parameters;
576 delete options.query_parameters;
579 delete options.query_parameters;
582 dataSet._match = options.criteria;
584 if(options.columns) {
585 var order = data.order;
586 order.forEach(function (e,i) {
587 var order_col = e.column;
588 var order_by = options.columns[order_col].data;
589 var order_dir = e.dir == 'asc' ? '+' : '-';
590 dataSet._order_by = order_dir + (!order_by.includes('.')?'me.'+order_by:order_by);
602 var included_ids = [];
604 $(columns_settings).each( function() {
605 var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
606 var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
607 if ( used_id == -1 ) return;
609 if ( this['is_hidden'] == "1" ) {
610 hidden_ids.push( used_id );
612 if ( this['cannot_be_toggled'] == "0" ) {
613 included_ids.push( used_id );
618 var exportColumns = ":visible:not(.noExport)";
619 if( settings.hasOwnProperty("exportColumns") ){
620 // A custom buttons configuration has been passed from the page
621 exportColumns = settings["exportColumns"];
624 var export_format = {
625 body: function ( data, row, column, node ) {
626 var newnode = $(node);
628 if ( newnode.find(".noExport").length > 0 ) {
629 newnode = newnode.clone();
630 newnode.find(".noExport").remove();
633 return newnode.text().replace( /\n/g, ' ' ).trim();
637 var export_buttons = [
639 extend: 'excelHtml5',
642 columns: exportColumns,
643 format: export_format
650 columns: exportColumns,
651 format: export_format
658 columns: exportColumns,
659 format: export_format
666 columns: exportColumns,
667 format: export_format
672 settings[ "buttons" ] = [
675 className: "dt_button_clear_filter",
676 titleAttr: _("Clear filter"),
678 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + _("Clear filter") + '</span>',
679 action: function ( e, dt, node, config ) {
680 dt.search( "" ).draw("page");
681 node.addClass("disabled");
686 if( included_ids.length > 0 ){
687 settings[ "buttons" ].push(
691 columns: included_ids,
692 className: "columns_controls",
693 titleAttr: _("Columns settings"),
694 text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + _("Columns") + '</span>',
696 columns: exportColumns
702 settings[ "buttons" ].push(
704 extend: 'collection',
707 className: "export_controls",
708 titleAttr: _("Export or print"),
709 text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + _("Export") + '</span>',
710 buttons: export_buttons
715 // Duplicate the table header row for columnFilter
716 thead_row = this.find('thead tr');
717 clone = thead_row.clone().addClass('filters_row');
718 clone.find("th.NoSort").html('');
719 thead_row.before(clone);
722 $(".dt_button_clear_filter, .columns_controls, .export_controls").tooltip();
724 return $(this).dataTable(settings);