Quantcast
Channel: Recent Discussions — DataTables forums
Viewing all 82284 articles
Browse latest View live

Manual sorting using a hidden column

$
0
0

I have a column my users want to sort by that doesn't contain values that are reasonably sortable. The sort order the users want to achieve is rather psycho-logical than logical.

I built a solution that allows the user to click on the sorting symbols in the column header. Subsequently the table is sorted by using values from a hidden column. For the user it feels like the table was sorted using the values from the column she clicked on.

I could only achieve this messing around with jQuery which I don't like. I didn't find anything suitable in the API. Question: Is there anything usable for this purpose in the API?

This is my solution:
The user sees open tasks and can order the contracts by the earliest task due date a contract has. If the contract has several tasks with several due dates the following due dates of that contract are being ignored for sorting.

This is what it looks like. Contracts with at least one overdue task are red.

The column is "Offene Aufgaben" the sorting symbol is "fake" if you will. If the user clicks on it the table is sorted by a hidden column.

HTML: the "Offene Aufgaben" column and the hidden column are marked in yellow.

Column "Weitere Ereignisse" is renamed to "Offene Aufgaben" later - so don't be confused ...

And here is the javascript code. (The data table is used on multiple pages in different configurations. We are on "inboxTasksPage" here. The ids to look for are "furtherEventsCol" and "minTaskDueDate". "furtherEventsCol" Column has "orderable: false" set.

//has to be set on top of the code because the columns will be hidden - then the jquery
//command does not work any longer!
var ixOrder; var descAsc;
if ( inboxTasksPage ) {
    ixOrder = $('#minTaskDueDate').index();
    descAsc = 'asc';
} else {
    ixOrder = $('#updateTime').index();
    descAsc = 'desc';
} 
......
if ( inboxTasksPage ) {
    //first click on OpenTasks causes descending order because the initial order
    //is by OpenTasks (furtherEventsCol) ascending
    var clickCounter = 0;
    //table was ordered initially by column #minTaskDueDate which contains the
    //minimum due dates of each contract with open tasks
    $('#tblCtrManagement').on( 'click', 'th:not(#furtherEventsCol)', function () {        
        clickCounter = 1; //next click on OpenTasks will cause ascending order
        $('th#furtherEventsCol').addClass('sorting');
        $('th#furtherEventsCol').removeClass('sorting_asc sorting_desc');
    } );
    $('#tblCtrManagement').on( 'click', 'th#furtherEventsCol', function () { 
        clickCounter++;
        $('th#furtherEventsCol').removeClass('sorting sorting_asc sorting_desc');
        if ( clickCounter % 2 == 0 ) { //even click number
            ctrTable.order([ ixOrder, 'asc' ]).draw();
            $('th#furtherEventsCol').addClass('sorting_asc');
        } else { //odd click number
            ctrTable.order([ ixOrder, 'desc' ]).draw();
            $('th#furtherEventsCol').addClass('sorting_desc');
        }
    } );
}

can i change coulmn direction on excel export on datatable say reverse direction

$
0
0

can i change column direction on excel export on datatable say reverse direction bsc it's appear in table in correct way after export it reverse

Filtering and orderable false

$
0
0

I have the following script:

<script>
       $(document).ready( function () {
       var table = $('#myTable').dataTable( {  
       "order":[[1,"desc"],[2,"desc"],[3,"desc"],[4,"desc"],[5,"desc"]],
       "dom": '<lif<t>p>',                                                 
       lengthMenu: [[100,10,25,50,-1],[100,10,25,50,"All"]],               
       fixedHeader: {headerOffset: 80},
                           
       columnDefs: [                                                       
                   { targets: [1,2,3,7,8], className: 'dt-body-center'},
                   { targets: [4,5,6,9], className: 'dt-body-right'},
                   { targets: [1], render: DataTable.render.number( ',', '.' )},
                   { targets: [7], render: DataTable.render.number( ',', '.', 0, '$' )}
                   ]
                        
                }); 
           } );
  </script>

And I don't know how to include the following code inside this...

var table = $('#example').DataTable();
 
var filteredData = table
    .column( 0 )
    .data()
    .filter( function ( value, index ) {
        return value > 20 ? true : false;
    } );

also I tried adding the following to disallow ordering and this would not work.

{ targets: [ 0, 1, 2, 3, 4, 5 ], orderable: false },

Any assistance would be appreciated.

Milton.

Uncaught TypeError: $.fn.dataTable.Editor is not a constructor

$
0
0

Hi!

I tried to add datatable with editor in wordpress using code from simple.html example.

datatable works fine, but as soon, as I try to add javascript for editor, I get:

Uncaught TypeError: $.fn.dataTable.Editor is not a constructor

Exmaple-Page

Any ideas?

Thanks
Digo

How can I pass variable from stored session or route (nodejs) to use it in ColumnDefs?

$
0
0

How can I pass variable from stored session or route (nodejs) to use it in ColumnDefs to filter buttons by usergroup permission?

"columnDefs": [
             {"data":null,
             "render":function(data, type, row, meta){
                 return data[0],data[1],data[2],data[3],data[4],data[5];
                 }
             },
             {"targets":4, render:function(data){
                 return moment(data).format('YYYY-MM-DD HH:mm');
                 }
             },
             {"targets":5, render:function(data){
                 return moment(data).format('YYYY-MM-DD HH:mm');
                 }
             },
             {"targets":-1,
             "searchable": false,
             "data":null,
             "render":function(data, type, row, meta){
                 return `<div class="btn-group" role="group"> 
                 <a id="icon" class="text-dark border-0 rounded-0" href="/edit/`+ data[0] +`">
                     <svg xmlns="http://www.w3.org/2000/svg" width="17" height="20" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16">
                         <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456l-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z"/>
                         <path fill-rule="evenodd" d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"/>
                     </svg>
                 </a>
                 </div>` 
                 ;}
             }
         ]

I want to make more buttons like this on up but only show them to specific usergroup.
I have session store in my DB and on client side it was easy becouse there I coudl use something like this from render result:

<% if (user.usergroup == "superadmin") { %> 
<a href ....

Now I have problem at server side. Not using editor and can't pass this usergroup from session to read it in columnDefs.

This is function to render file to show datatable:

    data: async (req,res) => {
        const ssn = req.session;
        res.render('data.ejs', {
            title: ""
            ,message:''
            ,usergroup: ssn.usergroup
            ,loggeduser: ssn.username
            ,fullname: ssn.fullname
            ,subcat1: ssn.subcat1 
            ,subcat2: ssn.subcat2
            ,usercat: ssn.usercat 
            
        });
        

    },

and another one to send data from database:

dataTable: (req, res) => {
        const requestQuery = req.query;
        const ssn = req.session;
        const usergroup = ssn.usergroup;
        let columnsMap = [
            {
                db: "id",
                dt: 0
            },
            {
                db: "category",
                dt: 1
            },
            {
                db: "topic",
                dt: 2
            },
            {
                db: "rodzaj",
                dt: 3
            },
            {
                db: "send_date",
                dt: 4
            },
            {
                db: "update_date",
                dt: 5
            },
            {  
                db: "author",
                dt: 6
            },
            {  
                db: "author",
                dt: 7
            }


          ];

       
          const primaryKey = "id"
          let query = `my query`;
          
          const nodeTable = new NodeTable(requestQuery, db, query, primaryKey, columnsMap);
         
          nodeTable.output((err, data)=>{
            if (err) {
              console.log(err);
              return;
            }
            //console.log("data: ",data);
            // Directly send this data as output to Datatable
            res.send(data)
          })
    },

Using https://www.npmjs.com/package/nodetable

Node.js - where condition only works as object or inside knex function

$
0
0

Hoi,

seems like this problem was previously discussed, but documentation on homepage needs to be updated accordingly or the problem needs a fix.

(https://datatables.net/forums/discussion/60782/node-js-where-clause-stopped-working-after-updating-knex)

This wont work:

editor.where( 'user_id', 12 );

but the object variant works:

editor.where( {
    user_id: 12
} )

The object variant doesn't allow conditions, so I have to write the function variant as follows:

editor.where( function () {
    this.where( 'user_id', '>', 12 );
} );

Cheers
Hannes

How to disable sort table on click?

$
0
0

I would like to know if it is possible to disable that when clicking on the th nothing happens in the table nor is it ordered

data range filter

$
0
0

Im using this example: https://datatables.net/extensions/datetime/examples/integration/datatables.html
What im i doing wrong? the problem is that with my code the calendar appears in two langues, english and spanish, it is in spanish but after a click it turns back to english i only want my code to have the spanish calendar. this is how my code looks like:

$(document).ready(function() { new DateTime(document.getElementById('min'), { i18n: { previous: 'Précédent', next: 'Premier', months: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ], weekdays: [ 'Dom', 'Lun', 'Mar', 'Mier', 'Jue', 'Vie', 'Sab' ] } }); new DateTime(document.getElementById('max'), { i18n: { previous: 'Précédent', next: 'Premier', months: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ], weekdays: [ 'Dom', 'Lun', 'Mar', 'Mier', 'Jue', 'Vie', 'Sab' ] } }); }); $(document).ready(function() { var minDate, maxDate; // Custom filtering function which will search data in column four between two values $.fn.dataTable.ext.search.push( function( settings, data, dataIndex ) { var min = minDate.val(); var max = maxDate.val(); var date = new Date( data[0] ); if ( ( min === null && max === null ) || ( min === null && date <= max ) || ( min <= date && max === null ) || ( min <= date && date <= max ) ) { return true; } return false; } ); // Create date inputs minDate = new DateTime($('#min'), { format: ' DD/MM/YYYY' }); maxDate = new DateTime($('#max'), { format: 'DD/MM/YYYY' }); // DataTables initialisation var table = $('#myTable').DataTable(); // Refilter the table $('#min, #max').on('change', function () { table.draw(); }); }); </script>

how to get selected data on inline button ?

$
0
0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem:

Hi,

I try to get selected data on the inline button like this , but does not wrok !

// Edit record
$('#my_table').on('click', 'td.editor-edit', function (e) {
    e.preventDefault();

            var count = table.rows( { selected: true } ).count();

             alert('count = '+count);

} );

Thanks.
Mikael

using datatables in a popup - editors show only in the background and do not work

$
0
0

Hi,

I have a quite normal datatable, only it is sitting in a popup-window called with

ajax_call('Core', 'XShowPopupNew', '__plugName__:__instance__', 'textvorlage')

Everything works fine, only I can not show any editors. Those appear kind of "inbetween the popup and the main site. If I close my popup, th editor then is in the foreground, but not working - I guess because I closed the site where it refers to.

I could solve most problems by using inline-editing, but for delete this can not work. Even if I use this code (that shouldnt display any editor as I believe)

                {
                    extend: "selectedSingle",
                    text: "löschen",
                    action: function ( e, dt, node, config ) {
                        editor_posvorl
                                .edit( table.row( { selected: true } ).index(), false )
                                .set( 'geloescht', 1 )
                                .submit();
                    }
                },

nothing happens at all.
Any ideas what do to?

Thanks Max

content: "↑"; in ordering arrows

$
0
0

Hello guys,
sorry but i can't post a jsfiddle link for this issue because it happens randomly so i attached a screenshot.
I'm using latest datatables in a laravel project with bootstrap 4.6. I also tested it with bootstrap 5 beta 3.

Refreshing the page solves the issue

Any idea ?

The

SearchPanes cascadePanes doesn't work with nightly build

Requesting an isSelected() method in the API

Brand new to DataTables - DataTables warning: table id=lenderTable - Requested unknown parameter '5'

$
0
0

I have new ASP.NET Core 5 MVC app that I am adding DataTables to.
I have a controller method is that called via the ajax in the DataTable and returns json.
Here is my javascript I wrote:

$(document).ready(function () {
        $('#lenderTable').dataTable({
            "processing": true, // for show progress bar
            "serverSide": true, // for process server side
            "filter": true, // this is for disable filter (search box)
            "orderMulti": false, // for disable multiple column at once
            "ajax": {
                "url": "/Admin/GetLenders",
                "type": "POST",
                "datatype": "json"
            },
            "columnDefs": [{
                "targets": [0],
                "visible": false,
                "searchable": false
            }],
            "columns": [
                { "data": "id" },
                { "data": "lenderName" },
                { "data": "lenderCode" },
                { "data": "modifiedOn" },
                { "data": "status" },
                {
                    "render": function (data, type, row, meta) { return '<a class="btn btn-info" href="/Lender/Edit/' + row.id + '">Edit</a>'; }
                },
                {
                    data: null,
                    render: function (data, type, row) {
                        return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.id + "'); >Delete</a>";
                    }
                },
            ]

        });
    });

I get the full error of:
DataTables warning: table id=lenderTable - Requested unknown parameter '5' for row 0, column 5.

All of the data otherwise gets loaded correctly despite the error.

I have looked the documentation and I dont understand what the problem is.

datatable

$
0
0

jquery().dattable() is not a function


I am using datatable in my react project. How to rename the column title on performing some action?

$
0
0

Eg:

Initially my table has two columns as below:

Name age

After some action, I want to change the title as like this

Name. age < 20

datatables - filtering several fields with one Ajax

$
0
0

I have a datatables library. I made a dynamic Ajax table but I have a problem with sorting 3 fields at once. currently I have done that after clicking filter, three AJAX requests are sent:

<table class="table table-hover" id="datatable-ajax-1" style="font-size: 0.75em;"> <thead> <tr> <th style="text-align: left;"></th> <th style="text-align: left;">Treść logu</th> <th style="text-align: left;">Źródło</th> <th style="text-align: left;">Data</th> <th style="text-align: left;"></th> </tr> </thead> <tfoot class="alert alert-info"> <tr> <th></th> <th> <div class="row"> <div class="col-sm-12 action-type"> <select id="action-type" name="action-type" multiple> <option value="addPolicy">Dodanie dokumentu: Polisa</option> <option value="add_task">Dodanie nowego zadania</option> <option value="addPayments">Dodanie płatności</option> <option value="addChat">Dodanie wiadomości czat</option> <option value="addOrder">Dodanie zamówienia</option> <option value="addOrderToInsly">Dodanie zamówienia do INSLY</option> <option value="editPolicy">Edycja dokumentu: Polisa</option> <option value="showDocuments">Pokazanie dokumentów</option> <option value="showOffer">Pokazanie ofert</option> <option value="phone_connection">Połączenie z telefonem</option> <option value="delete_task">Usunięcie zadania</option> <option value="notice_order">Wygenerowanie wypowiedzenia systemowego</option> <option value="close_task">Zakończenie zadania</option> <option value="update_task">Zaktualizowanie zadania</option> <option value="changeName_order">Zmiana nazwy zamówienia</option> <option value="newAdmin_order">Zmiana opiekuna zamówienia</option> <option value="newAdmin_task">Zmiana osoby odpowiedzialnej za zadanie</option> <option value="changeStatus_order">Zmiana statusu zamówienia</option> </select> </div> </div> </th> <th> <div class="row"> <div class="col-sm-12 action-source"> <select id="action-source" name="action-source" multiple> <option value="communication.mySMS.logs">communication.mySMS.logs</option> <option value="orders_logs">orders_logs</option> <option value="tasks_logs">tasks_logs</option> <option value="connections_made">connections_made</option> <option value="emails_logs">emails_logs</option> <option value="orders_automaticFill_logs">orders_automaticFill_logs</option> <option value="orders_messages">orders_messages</option> <option value="orders_status_logs">orders_status_logs</option> </select> </div> </div> </th> <th> <div class="row"> <div class="form-group col-sm-12"> <div class="input-group"> <span class="input-group-btn"> <button type="button" class="btn btn-fields"><i class="fas fa-calendar-day" aria-hidden="true"></i></button> </span> <input type="text" id="date-range" name="date-range" class="form-control" placeholder="Wybierz zakres daty" style="background-color: #FFF; border-color: #efefef;" readonly /> </div> </div> </div> </th> <th> <div class="row"> <div class="form-group col-sm-12"> <div class="input-group"> <button class="btn btn-primary profile-button" id="buttonFilter">Filtruj</button> </div> </div> </div> </th> </tr> </tfoot> </table>

`$(function(){
$.fn.dataTable.defaults.column.asSorting = ['desc', 'asc'];
var dataTable1 = $('#datatable-ajax-1').dataTable({
order: [[ 0, "desc" ]],
dom:
"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>"+
"<'row'<'col-sm-12'B>>",
"stateSave": true,
buttons: [
<?php if(acl_get('type')=="super_admin"): ?> 'csv' <?php endif; ?>
],
"language": {
"url": "<?php echo base_url();?>assets/global/plugins/datatables/Polish.json"
},
"colVis": {
"buttonText": "Pokaż/Ukryj kolumny"
},
"autoWidth": false,
"processing": true,
"serverSide": true,
"columns": [
{"data":"icon","orderable": false},
{"data":"message","orderable": false},
{"data":"source","orderable": false},
{"data":"date","orderable": false},
{"data":"action","orderable": false},
],
"ajax": {
"dataType": "jsonp",
"url": "<?php echo site_url('admin/datatable/admins/index/');?>",
"data": {
"admin_id": <?=$admin->id;?>
}
}
});

$("#buttonFilter").click(function() {
    dataTable1.fnFilter($('#action-type').val(), '1' );
    dataTable1.fnFilter($('#action-source').val(), '2' );
    dataTable1.fnFilter($('input[name="date-range"]').val(), '3');
});

});`

Anyone have an idea how to solve this problem? :(

[Accessibility][Pagination] Using actual buttons instead of links

$
0
0

Hello, for accessibility purposes I realized that what looks like buttons in the pagination panel is currently built with links (<a> tags) instead of using actual buttons (<button> tag).

I tried to modify the generated DOM in order to replace links with buttons but it seems that Datatable doesn't handle the actions on the buttons and therefore this attempt failed.

It seems rather simple to change the way the DOM is generated in Datatable code (https://github.com/DataTables/DataTablesSrc/blob/master/js/ext/ext.paging.js lines 147 to 157), but I cannot figure why actual buttons are not correctly taken into account?

How to export all records into excel in Serverside datatables?

$
0
0

I'm calling below actions method in

  "buttons": [
                             {

                                "extend": 'excel',
                                "text": '<button class="btn"><i class="fa fa-file-excel-o" style="color: green;"></i>Export</button>',
                                "titleAttr": 'Excel',
                                "action": newexportaction,
                                "exportOptions": {
                                    columns: ':not(:last-child)',
                                },
                                "filename": function () {
                                    var d = new Date();
                                    var l = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
                                    var n = d.getHours() + "-" + d.getMinutes() + "-" + d.getSeconds();
                                    return 'List_' + l + ' ' + n;
                                },
                            },
                        ],
`function newexportaction(e, dt, button, config) {
    var self = this;
    var oldStart = dt.settings()[0]._iDisplayStart;
    dt.one('preXhr', function (e, s, data) {
        // Just this once, load all data from the server...
        data.start = 0;
        data.length = 2147483647;
        dt.one('preDraw', function (e, settings) {
            // Call the original action function
            if (button[0].className.indexOf('buttons-copy') >= 0) {
                $.fn.dataTable.ext.buttons.copyHtml5.action.call(self, e, dt, button, config);
            } else if (button[0].className.indexOf('buttons-excel') >= 0) {
                $.fn.dataTable.ext.buttons.excelHtml5.available(dt, config) ?
                    $.fn.dataTable.ext.buttons.excelHtml5.action.call(self, e, dt, button, config) :
                    $.fn.dataTable.ext.buttons.excelFlash.action.call(self, e, dt, button, config);
            } else if (button[0].className.indexOf('buttons-csv') >= 0) {
                $.fn.dataTable.ext.buttons.csvHtml5.available(dt, config) ?
                    $.fn.dataTable.ext.buttons.csvHtml5.action.call(self, e, dt, button, config) :
                    $.fn.dataTable.ext.buttons.csvFlash.action.call(self, e, dt, button, config);
            } else if (button[0].className.indexOf('buttons-pdf') >= 0) {
                $.fn.dataTable.ext.buttons.pdfHtml5.available(dt, config) ?
                    $.fn.dataTable.ext.buttons.pdfHtml5.action.call(self, e, dt, button, config) :
                    $.fn.dataTable.ext.buttons.pdfFlash.action.call(self, e, dt, button, config);
            } else if (button[0].className.indexOf('buttons-print') >= 0) {
                $.fn.dataTable.ext.buttons.print.action(e, dt, button, config);
            }
            dt.one('preXhr', function (e, s, data) {
                // DataTables thinks the first item displayed is index 0, but we're not drawing that.
                // Set the property to what it was before exporting.
                settings._iDisplayStart = oldStart;
                data.start = oldStart;
            });
            // Reload the grid with the original page. Otherwise, API functions like table.cell(this) don't work properly.
            setTimeout(dt.ajax.reload, 0);
            // Prevent rendering of the full data to the DOM
            return false;
        });
    });
    // Requery the server with the new one-time export settings
    dt.ajax.reload();
};`

Once action method is called data is start fetching but after sometime I'm getting JSON serialize error.
Like data length is exceed the defined value.
please give some advice how to proceed further.

Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

How to switch the timezone of DateTime from UTC to other when using the date range filter

$
0
0

Hi All,
I am new to frontend and Datatable. When I tried to use date range filter, the timezone of datetime shown in the calender is UTC, and I wanted that datetime to show in EST. Below are the figures, I have the datetime range work on the third column.
As you can see, when datetime range started by 05:05, there are two entries displayed, which arrival time is 00:05 by EST and 05:05 by UTC. And when datetime range started by 05:06, two entries are no longer displayed. Can anyone tell me how to have date filter show the time in EST, instead of UTC?

Viewing all 82284 articles
Browse latest View live