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

SUM of a column based on value of another column

$
0
0

I have 10 column into datatable table . In which I want do sum for column 8 based on the value of column 3. I want to exclude value of column 8 from SUM where value for the same row in column 3 is "waiting response" and I want SUM of distinct value of column3.

My table is looks like in image
!

or you can check image here: https://pasteboard.co/H0iCJqA.png


Server Side paging has no effect on backend using PHP DataTables Editor class

$
0
0

DataTable Settings: serverSide: true, processing: true, lengthChange: false, select: true
Ajax request sent: [draw] => 1 [start] => 0 [length] => 10
Query generated by Editor class has no limits and is selecting the ~92k records.
Observing the response - entire lot of 92k records is sent back.

maximum call stack size exceeded in export

$
0
0

Hello when i export a small table to excel it works fine
but when i try to export same table but with lots of rows from 20,000 to 60,000 it throws
RangeError: Maximum call stack size exceeded
exception.

how to use mergeCells

confirmation on form close

$
0
0

Referencing https://datatables.net/forums/discussion/32883, I tried this implementation. I see (at least on Chrome) that if I use ESC, the popup is displayed twice, but Cancel does indeed bring user back to form to continue editing. If I close the form using the X in the upper right, however, the form closes whether I click OK or Cancel.

Is there something I'm doing wrong? I can set up test area for you again if needed.

In case there is some conflict specific to my processing, my full event handler setup is

// this must be done after datatables() is called in datatables.js
var openVals;
function afterdatatables(){
    editor.on( 'uploadXhrSuccess', function ( e, fieldName, json ) {
        console.log ('elev = ' + json.elev + ' distance = ' + json.distance);
        editor.field('elev').set(json.elev);
        editor.field('distance').set(json.distance);
        editor.field('active').set(json.active);
        editor.field('location').set(json.location);
    } );

    editor.on('initCreate', function() {
        editor.set('active', 1)
        editor.field('active').hide()
    });

    editor.on('initEdit', function() {
        var fileid = editor.get('fileid');
        editor.set('turns', 'Loading...')
        editor.field('active').show()
        $.ajax({
            // rr_turns_url_prefix comes from runningroute-*-config.js
            url: rr_turns_url_prefix + '/admin/' + fileid + '/turns',
            success : function(data) {
                editor.set('turns', data.turns)
            },
            error : function(jqXHR, textStatus, errorThrown) {
                editor.set('turns', 'ERROR: could not retrieve turn data\n'
                            + '   ' + errorThrown)
            },
        });

    });

    // confirm before closing window for unsaved changes
    // from https://datatables.net/forums/discussion/32883
    editor
        .on( 'open', function () {
            // Store the values of the fields on open
            openVals = JSON.stringify( editor.get() );
        } )
       .on( 'preClose', function ( e ) {
            // On close, check if the values have changed and ask for closing confirmation if they have
            if ( openVals !== JSON.stringify( editor.get() ) ) {
                return confirm( 'You have unsaved changes. Are you sure you want to exit?' );
            }
        } )
       .on( 'preBlur', function ( e ) {
            // On close, check if the values have changed and ask for closing confirmation if they have
            if ( openVals !== JSON.stringify( editor.get() ) ) {
                return confirm( 'You have unsaved changes. Are you sure you want to exit?' );
            }
    } );
};

Proper Syntax for Initializing "Order" Functionality

$
0
0

I am trying to use the "order" functionality to sort the 9th column in my table by default. When I try to initialize the datatables using the code below, the datatables functionality fails to appear on page load (HTML table is present, though).

I believe I have followed the documentation for "order" correctly. Any obvious problems in my initialization code below?

https://datatables.net/examples/basic_init/table_sorting.html

<!-- Link out for Jquery, which is a dependency for datatables -->

<script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>

<!-- Link out for datatables -->

<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.4.2/css/buttons.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.4.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/buttons/1.4.2/js/buttons.print.min.js"></script>

<script language="javascript">

$(document).ready( function () {
    $('#table_id').DataTable( {
          "order": [[10, "desc"]]
          dom: 'Bfrtip' ,
          buttons: [
              'pageLength',
              'print'
          ]
    }  );
} );

</script>

About modify data row object

$
0
0

I have a little question about when modify DataTable data row.
For example:

// Object DataTable get data row
var dataCell = Dtable.row(row).data();
dataCell.id = 10;

When I modify the property value of data object row, in automatically modify in the DataTable JavaScript Object? And is not necessary to do

Dtable.row(row).data(dataCell);
Dtable.row(row).invalidate();  // Is necessary to Add .draw() when invalidate()?
// Or to do
Dtable.rows().invalidate();  // Is necessary to Add .draw() when invalidate()?

I understood what I need to execute .draw() when I want to update the DOM, but is not clear for me how works .invalidate() and if the data row object is modify automatically modify de JavaScript Object contained by DataTable instance.

I'm waiting for you feedback.

Editor and UUID primary keys?

$
0
0

I've been thinking about switching to UUID primary keys instead of sequence id's. Just a general question of anybody doing this and what problems if any need addressed? It doesn't appear to me that Editor really cares what you use as the primary id as long as its unique. As it uses an internal index anyway it seems that there shouldn't be a performance hit either? I'm guessing I'll need to do a getter and a setter on the server scripts to convert back and forth between the DB internal 128 bit data type (I'm using Postgres) and the javascript string representation? Main motivation here is the use of multiple remote databases and the need to manage primary keys across all of them in a simple way. Alternative is to simply assign different sequence ranges on each db but it seems I might live to regret that some day as it scales out. Am I missing anything or is this just a dumb idea to begin with?


how to set a different timeout?

$
0
0

Hi,

i need to change the timeout wait for a page, now is set on 30 second but i need more time to elaborate the records.

Thanks

Search does not work

$
0
0

I'm having difficulty implementing the Editor with join, the server side works perfectly, but the search and pagination are not working as it should.

Sort Arrow Icons Position

$
0
0

Hi,

I have been using dataTables for a few months now and am really impressed with its capabilities.

For the dataTable I am working on currently I have activated the column sort in addition to a drop down filter for the header and a textbox filter for the footer.

Everything works but I would like to move the position of the sort arrows as they are clicked/activated every time the drop down filter is clicked - which is not ideal from a usablility point of view.

I can move the drop down filter boxes using the 'orderCellsTop: false' attribute, but the sort arrow icons also move with the drop down boxes.

I found the following solution which puts the drop down boxes in a custom css class (.filterhead) but this then creates a ghost row in the table and stops the footer filters from working.

$(".filterhead").each( function ( i ) {
    var select = $('<select><option value=""></option></select>')
        .appendTo( $(this).empty() )
        .on( 'change', function () {
               var term = $(this).val();
            table.column( i ).search(term, false, false ).draw();
        } );
         table.column( i ).data().unique().sort().each( function ( d, j ) {
            select.append( '<option value="'+d+'">'+d+'</option>' )
        } );
    } );

I have been searching for a solution for quite a while, both CSS and dataTables, but unfortunately I cannot find one.

I am using the Bootstrap4 css theme.

Here is my dataTables code -

$(document).ready(function () {

    // Setup - add a text input to each footer cell
    $('#searchResults tfoot th').each( function () {
        var title = $('#searchResults thead th').eq( $(this).index() ).text();
        //$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
        $(this).html( '<input type="text" placeholder="Filter" />' );
    } );


    /* DC: this is for DataTables 1.12 */
    var table = $('#searchResults').DataTable( {
        "data": <?php if (count($this->data)){ echo $this->data; } else { echo "''"; } ?>,
        "paging":   true,
        "autoWidth": false,
        "stateSave": false,
        "order": [],
        "language": {
          "emptyTable": "No search results found"
        },
        "pagingType": "full_numbers",
        "searching": true,
        "scrollX": true,
        "scrollCollapse": true,
         // DC: use this initComplete setting if you want the select drop down filters to be put in the standard <thead><tr><th> cells
        "initComplete": function () { // DC: this adds the select menus at col header (can be changed to footer - just ensure there is a free <tr> in dataTable)
            this.api().columns().every( function () {
                var column = this;
                var select = $('<select><option value=""></option></select>')
                    .appendTo( $(column.header()).empty() )
                    .on( 'change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );

                        column
                            .search( val ? '^'+val+'$' : '', true, false )
                            .draw();
                    } );

                column.data().unique().sort().each( function ( d, j ) {
                    select.append( '<option value="'+d+'">'+d+'</option>' )
                } );
            } );
        },

        "orderCellsTop": false,
        "ordering": true,
    } );

    // Restore state
    var state = table.state.loaded();
    if ( state ) {
      table.columns().eq( 0 ).each( function ( colIdx ) {
        var colSearch = state.columns[colIdx].search;

        if ( colSearch.search ) {
          $( 'input', table.column( colIdx ).footer() ).val( colSearch.search );
        }
      } );

      table.draw();
    }

    // Apply the search
    table.columns().eq( 0 ).each( function ( colIdx ) {
        $( 'input', table.column( colIdx ).footer() ).on( 'keyup change', function () {
            table
                .column( colIdx )
                .search( this.value )
                .draw();
        } );
    } );
} );

Any help is appreciated.
Best Regards

DataTable error

DataTables warning: table id=manageConsultantTable - Invalid JSON response. For more information abo

$
0
0

Hi Guys,

I am ne wto using DataTables and am struggling with this error on my page. I try to debug and get the following which I cant thoroughly understand and solve. Please kindly assist me if you can. Have been on this for long without any breakthrough.

Thanks you
consultant.php:343 GET http://localhost/tms/admin/assests/plugins/fileinput/js/plugins/canvas-to-blob.min.js');%20?%3E net::ERR_ABORTED
GET http://localhost/tms/admin/assests/plugins/fileinput/js/plugins/canvas-to-blob.min.js');%20?%3E 404 (Not Found)
jquery.min.js:4 GET http://localhost/tms/admin/assests/plugins/images/sort_both.png 404 (Not Found)

Disable Edit, or read only row

$
0
0

I have the need to either disable the edit button. I have been successful with the js to select this data however it seems that the underlying scripts prevent this enable/disable from operating as expected for example via:
table.button( 1 ).enable( data === 1 );

Is there a means that I am over looking to make this function as intended? Alternatively, another option would be to mark a row as read only, is this a possibility?

TypeError: f[b] is not a function when clicking Update, New, Delete button

$
0
0

The table renders and displays the data yet, when trying to edit, delete, or add a new record, I get error:
TypeError: f[b] is not a function

Here is the debug:
http://debug.datatables.net/alujin

Here is the code:

var editor; // use a global for the submit and return data rendering in the examples

$(document).ready(function () {

       editor = new $.fn.dataTable.Editor({
            ajax: "/api/StudentImmigrationNotesDT",
            model: "StudentImmigrationNotesModel",
            table: "#ImmigrationNotes",
            fields: [{
                    label: "Advised Date:",
                    name: "imnAdvisingDate",
                    type: "datetime"
            }, {
                    label: "Action Given:",
                    name: "imnAdvisingAction",
            }, {
                    label: "Advise Type:",
                    name: "imnAdvisingType",
           }, {
                    label: "Note:",
                    name: "imnAdvisingNote",
            }, {
                label: "Source:",
                name: "imnAdvisingSource",
           }, {
               label: "School ID:",
               name: "imnSchoolMasterID",
            }, {
                label: "Student ID:",
                name: "imnStudentUserID",
           }, {
               label: "Advise ID:",
               name: "imnImmigrationNoteID",
           }
            ]
        });

        // setup and establish the DataTable
        $("#ImmigrationNotes").DataTable({
            ajax: "/api/StudentImmigrationNotesDT",
            model: "StudentImmigrationNotesModel",
            // the columns used
            //data: data,
            columns: [
                { data: 'Advised Date' },
                { data: 'Action Given' },
                { data: 'Advise Type' },
                { data: 'Advise Note' },
                { data: 'Advise Source' },
                { data: 'School ID' },
                { data: 'Student ID' },
                { data: 'Advise ID' }
            ],
            // this sets the feedback text
            "oLanguage": {
                //"sUrl": "media/language/de_DE.txt",
                "sZeroRecords": "No records match your search criterion.",
                "sLengthMenu": "Display _MENU_ records per page.",
                "sInfo": "Displaying _START_ to _END_ of _TOTAL_ records.",
                "sInfoEmpty": "Showing 0 to 0 of 0 records.",
                "sInfoFiltered": "(Filtered from _MAX_ total records.)"
            },
            // this is for the copy, export to Excel, Print and PDF
            //dom: '<"top"fil<"toolbar">p>rt<"bottom"Bil>',
            dom: '<"top"r<"toolbar">fl>rt<"bottom"Bpi>',
            buttons: [
                {
                    extend: 'copyHtml5',
                    //ButtonText: 'Copy Page',
                    exportOptions: {
                        rows: ':visible',
                        columns: ':visible'
                    },
                },
                {
                    extend: 'csvHtml5',
                    //ButtonText: "Export to CSV",
                    exportOptions: {
                        rows: ':visible',
                        columns: ':visible'
                    },

                },
                {
                    extend: 'excelHtml5',
                    //ButtonText: "Export to CSV",
                    exportOptions: {
                        rows: ':visible',
                        columns: ':visible'
                    },
                },
                {
                    extend: 'pdfHtml5',
                    //ButtonText: "PDF",
                    exportOptions: {
                        rows: ':visible',
                        columns: ':visible'
                    },
                },
                {
                    extend: 'print',
                    //ButtonText: "Print",
                    exportOptions: {
                        rows: ':visible',
                        columns: ':visible'
                    },
                },
                //'selectedSingle',
                'selectAll',
                'selectNone',
                //'selectRows',
                //'selectColumns',
                //'selectCells',

                //// this hides or shows columns
                //{
                //    extend: 'collection',
                //    text: 'Toggle Visibility',
                //    buttons: [
                //        {
                //            text: 'Recalled',
                //            action: function (e, dt, node, config) {
                //                dt.column(6).visible(!dt.column(6).visible());
                //            }
                //        },
                //        {
                //            text: 'Action',
                //            action: function (e, dt, node, config) {
                //                dt.column(7).visible(!dt.column(7).visible());
                //            }
                //        }
                //    ]
                //},

                { extend: "create", editor: editor },
                { extend: "edit", editor: editor },
                { extend: "remove", editor: editor }

            ],

            // default settings
            keys: false, // single cell select if true
            info: true,
            sort: true,
            searching: true,
            select: true,
            ordering: true,
            order: [[0, 'desc']],
            scrollY: '50vh',
            scrollX: true,
            scrollCollapse: true,
            bJQueryUI: true,
            sPaginationType: "full_numbers",
            displayStart: 0,
            stateSave: true,
            autoWidth: true,
            paging: true,
            fixedHeader: true,
            fixedColumns: false,
            columnReorder: true,
            serverSide: false,
            processing: true,
            deferRender: true,
            responsive: true,

            //columnDefs: [
            //             { width: '20%', targets: 0 }
            //            ],
            lengthMenu: [[1, 5, 10, 25, 50, 100, -1], [1, 5, 10, 25, 50, 100, "All"]],
            iCookieDuration: 60 * 60 * 24, // 1 day keep cookie
        });

Can Button Element Control Multiple DataTables

$
0
0

I would like to use Column Visibility to show/hide columns. Right now, I have two datatables with same column names.

How can I use one button to show/hide column with the same column names in the two tables at the same time?

Is the Editor compatible with CKEditor 5 or will it be?

$
0
0

Hey Allan,

Is Editor going to be compatible with CKEditor 5? I work for a web development company and we're trying to decide on if we should get CKEditor 5 or 4.

Prevent DataTable from collapsing Columns?

$
0
0

I set my dataTable to scroll:

$('#data-table').DataTable({
    destroy: true,
    aaData: res.data,
    aoColumns: [
        { "sTitle": "Order ID", "mData": "OrderID", "sClass": "left" },
        { "sTitle": "Order Date", "mData": "OrderDate", "sClass": "left" },
        { "sTitle": "First Name", "mData": "FirstName", "sClass": "left" },
        { "sTitle": "Last Name", "mData": "LastName", "sClass": "left" },
        { "sTitle": "Patient ID", "mData": "LicenseNumber", "sClass": "left" },
        { "sTitle": "Quantity", "mData": "Quantity", "sClass": "right" },
        { "sTitle": "Total Amount", "mData": "TotalAmount", "sClass": "right" },
        { "sTitle": "Application Type", "mData": "PersonType", "sClass": "left" },
        { "sTitle": "Expiration Date", "mData": "ExpiryUtc", "sClass": "right" },
        { "sTitle": "Reason", "mData": "Reason", "sClass": "left" },
    ],
    scrollX: true,   //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    scrollY: 300,   //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    scrollCollapse: true,
    responsive: true,
    colReorder: false,
    keys: true,
    select: true
});

But often if the initial view is too narrow, instead of presenting the data with a horizontal scroll bar. instead the data is shown with the first column have the detail "+" button and one or more columns are hidden. How can I force the dataTable NEVER to collapse data columns into the detail "+" section?

Also something is often hiding the horizontal scroll bar. If I have the dataTable showing with the horizontal scrollbar and no columns collapse, then manually resize the browser, often the H scrollbar disappears and then never comes back except WHILE resizing I will see a brief flash of the H scrollbar. Do you know what css draws the H scrollbar and how to force it to always show when present?"

P,S, - please update this forum to allow pasting of images directly into the post like you can do on Stack Overflow, or at least allow files and images to be uploaded from local storage, don't make us have to find some hosting service to upload our files and images to. Your "Attach image/file" button is grossly misnamed as it dosn't allow you to attach anything, instead it mearly is another name for an url link to another hosting service.

MVC5 Entity Framework Server Side

$
0
0

Hi im stuck in this problem for almost a week now i need help to create a server side pagination , sorting , filtering

ive done so many ways i found in internet but non work i already filter the data and its showing the problem is the pagination sorting and filtering

my table initialization
function testing3() {
$("#ModalSearchTable").dataTable().fnDestroy();
var searchVal = $("#ModalSearchValue").val();

    var table = $("#ModalSearchTable").dataTable({
        "searching": false,
        "dom": 'frtip',
        responsive: true,
        "oLanguage":
        {
            "oPaginate":
            {
                "sFirst": "<<",
                "sLast": ">>",
                "sNext": ">",
                "sPrevious": "<"
            },
            "sLengthMenu": "",
            "sZeroRecords": "No Records Found"
        },
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": '@Url.Action("GetSearchData", "BusinessCenters")',
        "fnServerData": function (sSource, aoData, fnCallback) {
            /* Add some data to send to the source, and send as 'POST' */
            aoData.push({ "name": "searchParam", "value": searchVal })
            $.ajax({
                "dataType": "JSON",
                "type": "GET",
                "url": sSource,
                "data": aoData,
                "success": fnCallback
            });
        },
        "columns": [
            { "data": "Id" ,
            "class": "hidden",
                "sTitle": "Id",
            },
            {
                "data": "Code",
                "sTitle": "Code",
            },
            {
                "data": "Name",
                "sTitle": "Name",
            }
        ]

    });
}

my jason request
public JsonResult GetSearchData(string searchParam)
{
var bussCtrs = db.BusinessCenters
.Where(x => searchParam == "*" || x.BussCtrCode.Contains(searchParam) || x.BussCtrName.Contains(searchParam))
.ToList()
.Select(x => new { Id = x.BussCtrId, Code = x.BussCtrCode, Name = x.BussCtrName });

        return Json(new { aaData = bussCtrs }, JsonRequestBehavior.AllowGet);
    }

responsive edit form not showing properly

$
0
0

When using responsive support in the editor on a small device, if I do an edit via a link that I have created in the row (as oppsed to an editor button), the edit form comes up blank. With a link in the datatable column that has the editor_edit class I do this:

$(this.$el).on('click','a.editor_edit', function(e) {
          e.preventDefault();
           editor.edit( $(this).closest('tr'), {
             title: 'Edit  record',
             buttons: 'Update'
          } );
});

and get a blank edit form - just the title bar and button. If I use the editor Edit button, it all works properly.

I am using Chrome Developer tools to test different devices.

If I go back to my normal desktop, the link in the datatable row works properly. So it is only when on a smaller device that I am having the issue.

I am including this style sheet for responsive:
https://cdn.datatables.net/responsive/2.2.1/css/responsive.dataTables.min.cs

When I inspect, I get

 <div data-dte-e="form_content" class="DTE_Form_Content"></div>

and the div is empty.

Thanks for any ideas.

Viewing all 79545 articles
Browse latest View live




Latest Images