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",
37 className: "dt_button_clear_filter",
38 titleAttr: window.MSG_CLEAR_FILTER,
40 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + window.MSG_CLEAR_FILTER + '</span>',
41 available: function ( dt ) {
42 // The "clear filter" button is made available if this test returns true
43 if( dt.settings()[0].aanFeatures.f ){ // aanFeatures.f is null if there is no search form
47 action: function ( e, dt, node ) {
48 dt.search( "" ).draw("page");
49 node.addClass("disabled");
52 initComplete: function( settings) {
53 var tableId = settings.nTable.id
54 // When the DataTables search function is triggered,
55 // enable or disable the "Clear filter" button based on
56 // the presence of a search string
57 $("#" + tableId ).on( 'search.dt', function ( e, settings ) {
58 if( settings.oPreviousSearch.sSearch == "" ){
59 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").addClass("disabled");
61 $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").removeClass("disabled");
68 // Return an array of string containing the values of a particular column
69 $.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
70 // check that we have a column id
71 if ( typeof iColumn == "undefined" ) return new Array();
72 // by default we only wany unique data
73 if ( typeof bUnique == "undefined" ) bUnique = true;
74 // by default we do want to only look at filtered data
75 if ( typeof bFiltered == "undefined" ) bFiltered = true;
76 // by default we do not wany to include empty values
77 if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
78 // list of rows which we're going to loop through
80 // use only filtered rows
81 if (bFiltered == true) aiRows = oSettings.aiDisplay;
83 else aiRows = oSettings.aiDisplayMaster; // all row numbers
86 var asResultData = new Array();
87 for (var i=0,c=aiRows.length; i<c; i++) {
89 var aData = this.fnGetData(iRow);
90 var sValue = aData[iColumn];
91 // ignore empty values?
92 if (bIgnoreEmpty == true && sValue.length == 0) continue;
93 // ignore unique values?
94 else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
95 // else push the value onto the result data array
96 else asResultData.push(sValue);
101 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
102 // These keys must not launch filtering
103 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
105 // Set a filtering delay for global search field
106 jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
108 * Inputs: object:oSettings - dataTables settings object - automatically given
109 * integer:iDelay - delay in milliseconds
110 * Usage: $('#example').dataTable().fnSetFilteringDelay(250);
111 * Author: Zygimantas Berziunas (www.zygimantas.com) and Allan Jardine
112 * License: GPL v2 or BSD 3 point style
113 * Contact: zygimantas.berziunas /AT\ hotmail.com
117 iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay;
119 this.each( function ( i ) {
120 $.fn.dataTableExt.iApiIndex = i;
124 sPreviousSearch = null,
125 anControl = $( 'input', _that.fnSettings().aanFeatures.f );
127 anControl.unbind( 'keyup.DT' ).bind( 'keyup.DT', function(event) {
129 if (blacklist_keys.indexOf(event.keyCode) != -1) {
131 }else if ( event.keyCode == '13' ) {
132 $.fn.dataTableExt.iApiIndex = i;
133 _that.fnFilter( $(this).val() );
135 if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
136 window.clearTimeout(oTimerId);
137 sPreviousSearch = anControl.val();
138 oTimerId = window.setTimeout(function() {
139 $.fn.dataTableExt.iApiIndex = i;
140 _that.fnFilter( anControl.val() );
151 // Add a filtering delay on general search and on all input (with a class 'filter')
152 jQuery.fn.dataTableExt.oApi.fnAddFilters = function ( oSettings, sClass, iDelay ) {
154 this.fnSetFilteringDelay(iDelay);
155 var filterTimerId = null;
156 $(table).find("input."+sClass).keyup(function(event) {
157 if (blacklist_keys.indexOf(event.keyCode) != -1) {
159 }else if ( event.keyCode == '13' ) {
160 table.fnFilter( $(this).val(), $(this).attr('data-column_num') );
162 window.clearTimeout(filterTimerId);
164 filterTimerId = window.setTimeout(function() {
165 table.fnFilter($(input).val(), $(input).attr('data-column_num'));
169 $(table).find("select."+sClass).on('change', function() {
170 table.fnFilter($(this).val(), $(this).attr('data-column_num'));
174 // Sorting on html contains
175 // <a href="foo.pl">bar</a> sort on 'bar'
176 function dt_overwrite_html_sorting_localeCompare() {
177 jQuery.fn.dataTableExt.oSort['html-asc'] = function(a,b) {
178 a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
179 b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
180 if (typeof(a.localeCompare == "function")) {
181 return a.localeCompare(b);
183 return (a > b) ? 1 : ((a < b) ? -1 : 0);
187 jQuery.fn.dataTableExt.oSort['html-desc'] = function(a,b) {
188 a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
189 b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
190 if(typeof(b.localeCompare == "function")) {
191 return b.localeCompare(a);
193 return (b > a) ? 1 : ((b < a) ? -1 : 0);
197 jQuery.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
198 var x = a.replace( /<.*?>/g, "" );
199 var y = b.replace( /<.*?>/g, "" );
202 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
205 jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
206 var x = a.replace( /<.*?>/g, "" );
207 var y = b.replace( /<.*?>/g, "" );
210 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
214 $.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
215 var x = a.replace( /<.*?>/g, "" );
216 var y = b.replace( /<.*?>/g, "" );
219 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
222 $.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
223 var x = a.replace( /<.*?>/g, "" );
224 var y = b.replace( /<.*?>/g, "" );
227 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
233 * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
234 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
235 * Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
236 * See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
238 function naturalSort (a, b) {
239 var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
240 sre = /(^[ ]*|[ ]*$)/g,
241 dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
242 hre = /^0x[0-9a-f]+$/i,
244 // convert all to strings and trim()
245 x = a.toString().replace(sre, '') || '',
246 y = b.toString().replace(sre, '') || '',
248 xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
249 yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
250 // numeric, hex or date detection
251 xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
252 yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
253 // first try and sort Hex codes or Dates
255 if ( xD < yD ) return -1;
256 else if ( xD > yD ) return 1;
257 // natural sorting through split numeric strings and default strings
258 for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
259 // find floats not starting with '0', string or 0 if not defined (Clint Priest)
260 var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
261 var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
262 // handle numeric vs string comparison - number < string - (Kyle Adams)
263 if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
264 // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
265 else if (typeof oFxNcL !== typeof oFyNcL) {
269 if (oFxNcL < oFyNcL) return -1;
270 if (oFxNcL > oFyNcL) return 1;
275 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
276 "natural-asc": function ( a, b ) {
277 return naturalSort(a,b);
280 "natural-desc": function ( a, b ) {
281 return naturalSort(a,b) * -1;
287 /* Plugin to allow sorting on data stored in a span's title attribute
289 * Ex: <td><span title="[% ISO_date %]">[% formatted_date %]</span></td>
291 * In DataTables config:
293 * { "sType": "title-string" },
295 * http://datatables.net/plug-ins/sorting#hidden_title_string
297 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
298 "title-string-pre": function ( a ) {
299 var m = a.match(/title="(.*?)"/);
300 if ( null !== m && m.length ) {
301 return m[1].toLowerCase();
306 "title-string-asc": function ( a, b ) {
307 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
310 "title-string-desc": function ( a, b ) {
311 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
315 /* Plugin to allow sorting on numeric data stored in a span's title attribute
317 * Ex: <td><span title="[% decimal_number_that_JS_parseFloat_accepts %]">
318 * [% formatted currency %]
321 * In DataTables config:
323 * { "sType": "title-numeric" },
325 * http://datatables.net/plug-ins/sorting#hidden_title
327 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
328 "title-numeric-pre": function ( a ) {
329 var x = a.match(/title="*(-?[0-9\.]+)/)[1];
330 return parseFloat( x );
333 "title-numeric-asc": function ( a, b ) {
334 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
337 "title-numeric-desc": function ( a, b ) {
338 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
344 /* Plugin to allow text sorting to ignore articles
346 * In DataTables config:
348 * { "sType": "anti-the" },
350 * Based on the plugin found here:
351 * http://datatables.net/plug-ins/sorting#anti_the
352 * Modified to exclude HTML tags from sorting
353 * Extended to accept a string of space-separated articles
354 * from a configuration file (in English, "a," "an," and "the")
357 var config_exclude_articles_from_sort = window.CONFIG_EXCLUDE_ARTICLES_FROM_SORT || "a an the";
358 if (config_exclude_articles_from_sort){
359 var articles = config_exclude_articles_from_sort.split(" ");
361 for(i=0;i<articles.length;i++){
362 rpattern += "^" + articles[i] + " ";
363 if(i < articles.length - 1){ rpattern += "|"; }
365 var re = new RegExp(rpattern, "i");
368 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
369 "anti-the-pre": function ( a ) {
370 var x = String(a).replace( /<[\s\S]*?>/g, "" );
372 var z = y.replace(re, "").toLowerCase();
376 "anti-the-asc": function ( a, b ) {
377 return ((a < b) ? -1 : ((a > b) ? 1 : 0));
380 "anti-the-desc": function ( a, b ) {
381 return ((a < b) ? 1 : ((a > b) ? -1 : 0));
387 // Remove string between NSB NSB characters
388 $.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
389 var pattern = new RegExp("\x88.*\x89");
390 a = a.replace(pattern, "");
391 b = b.replace(pattern, "");
392 return (a > b) ? 1 : ((a < b) ? -1 : 0);
394 $.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
395 var pattern = new RegExp("\x88.*\x89");
396 a = a.replace(pattern, "");
397 b = b.replace(pattern, "");
398 return (b > a) ? 1 : ((b < a) ? -1 : 0);
401 /* Define two custom functions (asc and desc) for basket callnumber sorting */
402 jQuery.fn.dataTableExt.oSort['callnumbers-asc'] = function(x,y) {
403 var x_array = x.split("<div>");
404 var y_array = y.split("<div>");
406 /* Pop the first elements, they are empty strings */
410 x_array = jQuery.map( x_array, function( a ) {
411 return parse_callnumber( a );
413 y_array = jQuery.map( y_array, function( a ) {
414 return parse_callnumber( a );
423 if ( !x ) { x = ""; }
424 if ( !y ) { y = ""; }
426 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
429 jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
430 var x_array = x.split("<div>");
431 var y_array = y.split("<div>");
433 /* Pop the first elements, they are empty strings */
437 x_array = jQuery.map( x_array, function( a ) {
438 return parse_callnumber( a );
440 y_array = jQuery.map( y_array, function( a ) {
441 return parse_callnumber( a );
450 if ( !x ) { x = ""; }
451 if ( !y ) { y = ""; }
453 return ((x < y) ? 1 : ((x > y) ? -1 : 0));
456 function parse_callnumber ( html ) {
457 var array = html.split('<span class="callnumber">');
459 array = array[1].split('</span>');
466 // see http://www.datatables.net/examples/advanced_init/footer_callback.html
467 function footer_column_sum( api, column_numbers ) {
468 // Remove the formatting to get integer data for summation
469 var intVal = function ( i ) {
470 if ( typeof i === 'number' ) {
471 if ( isNaN(i) ) return 0;
473 } else if ( typeof i === 'string' ) {
474 var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
475 if ( isNaN(value) ) return 0;
482 for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
483 var column_number = column_numbers[indice];
486 var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
487 $(cells).each(function(){
488 total += intVal( $(this).html() );
490 total /= 100; // Hard-coded decimal precision
493 $( api.column( column_number ).footer() ).html(total.format_price());
497 function filterDataTable( table, column, term ){
499 table.column( column ).search( term ).draw("page");
501 table.search( term ).draw("page");
505 jQuery.fn.dataTable.ext.errMode = function(settings, note, message) {
506 console.warn(message);
511 $.fn.api = function(options, columns_settings, add_filters) {
514 if(!options.criteria || ['contains', 'starts_with', 'ends_with', 'exact'].indexOf(options.criteria.toLowerCase()) === -1) options.criteria = 'contains';
515 options.criteria = options.criteria.toLowerCase();
516 settings = $.extend(true, {}, dataTablesDefaults, {
523 'emptyTable': (options.emptyTable) ? options.emptyTable : "No data available in table"
525 'pagingType': 'full',
530 'beforeSend': function(xhr, settings) {
533 xhr.setRequestHeader('x-koha-embed', Array.isArray(options.embed)?options.embed.join(','):options.embed);
535 if(options.header_filter && options.query_parameters) {
536 xhr.setRequestHeader('x-koha-query', options.query_parameters);
537 delete options.query_parameters;
540 'dataFilter': function(data, type) {
541 var json = {data: JSON.parse(data)};
542 if(total = this._xhr.getResponseHeader('x-total-count')) {
543 json.recordsTotal = total;
544 json.recordsFiltered = total;
546 return JSON.stringify(json);
548 'data': function( data, settings ) {
549 var length = data.length;
550 var start = data.start;
553 _page: Math.floor(start/length) + 1,
557 var filter = data.search.value;
558 var query_parameters = settings.aoColumns
559 .filter(function(col) {
560 return col.bSearchable && typeof col.data == 'string' && (data.columns[col.idx].search.value != '' || filter != '')
564 var value = data.columns[col.idx].search.value != '' ? data.columns[col.idx].search.value : filter;
565 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?'%':'')};
569 if(query_parameters.length) {
570 query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:query_parameters);
571 if(options.header_filter) {
572 options.query_parameters = query_parameters;
574 dataSet.q = query_parameters;
575 delete options.query_parameters;
578 delete options.query_parameters;
581 dataSet._match = options.criteria;
583 if(options.columns) {
584 var order = data.order;
585 order.forEach(function (e,i) {
586 var order_col = e.column;
587 var order_by = options.columns[order_col].data;
588 var order_dir = e.dir == 'asc' ? '+' : '-';
589 dataSet._order_by = order_dir + (!order_by.includes('.')?'me.'+order_by:order_by);
601 var included_ids = [];
603 $(columns_settings).each( function() {
604 var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
605 var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
606 if ( used_id == -1 ) return;
608 if ( this['is_hidden'] == "1" ) {
609 hidden_ids.push( used_id );
611 if ( this['cannot_be_toggled'] == "0" ) {
612 included_ids.push( used_id );
617 var exportColumns = ":visible:not(.noExport)";
618 if( settings.hasOwnProperty("exportColumns") ){
619 // A custom buttons configuration has been passed from the page
620 exportColumns = settings["exportColumns"];
623 var export_format = {
624 body: function ( data, row, column, node ) {
625 var newnode = $(node);
627 if ( newnode.find(".noExport").length > 0 ) {
628 newnode = newnode.clone();
629 newnode.find(".noExport").remove();
632 return newnode.text().replace( /\n/g, ' ' ).trim();
636 var export_buttons = [
638 extend: 'excelHtml5',
641 columns: exportColumns,
642 format: export_format
649 columns: exportColumns,
650 format: export_format
657 columns: exportColumns,
658 format: export_format
665 columns: exportColumns,
666 format: export_format
671 settings[ "buttons" ] = [
674 className: "dt_button_clear_filter",
675 titleAttr: _("Clear filter"),
677 text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + _("Clear filter") + '</span>',
678 action: function ( e, dt, node, config ) {
679 dt.search( "" ).draw("page");
680 node.addClass("disabled");
685 if( included_ids.length > 0 ){
686 settings[ "buttons" ].push(
690 columns: included_ids,
691 className: "columns_controls",
692 titleAttr: _("Columns settings"),
693 text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + _("Columns") + '</span>',
695 columns: exportColumns
701 settings[ "buttons" ].push(
703 extend: 'collection',
706 className: "export_controls",
707 titleAttr: _("Export or print"),
708 text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + _("Export") + '</span>',
709 buttons: export_buttons
714 // Duplicate the table header row for columnFilter
715 thead_row = this.find('thead tr');
716 clone = thead_row.clone().addClass('filters_row');
717 clone.find("th.NoSort").html('');
718 thead_row.before(clone);
721 $(".dt_button_clear_filter, .columns_controls, .export_controls").tooltip();
723 return $(this).dataTable(settings);