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

child-row expand button in responsivePriority

$
0
0

I have a table that works well. It is fairly simple.
It gets defined with this:

$.extend( $.fn.dataTable.defaults, {
    responsive: true
} );  
    var table = $('#example').DataTable( {
        dom: "Bfrtip",
        ajax: "somefile.php",
        columns: [
            { data: "FirstName" },
            { data: "LastName"},
            { data: "LevelofAccess"}
        ],
        select: true,
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ],
        columnDefs:[
            { targets: [2],
              createdCell: function (td, cellData, rowData, row, col) {
                if ( cellData == 'Not assigned' ) {
                  $(td).css('color', 'red');
                }
              }
            }
        ]
    } );

Everything works fine.
But I want it to behave such that when it is in a small screen, and there is room only for one column, the one that shows is the second column (1 in the array).
I tried { responsivePriority: 1, targets: 1 } in columns[] and also in columnDefs[]
It works in both.
The problem is that the child-row expand button does not display anymore. If I get the responsivePriority parameter, the button is back.

Any ideas of what the issue might be?


Updating other fields in Database - based on select

$
0
0

Hi Everyone

I've just used the bar bones of the editor to update tables I need to edit and its working great (using in-line editing). However, I'm not sure how to move forward on this. I have a screen that list of samples taken during a specific inspection. showing 1) Where it was taken 2) the item it was taken from (window, wall, etc) 3) it's Sample number.... in addition I'm displaying 2 additional "Results" selections - the "Result" and "Recommended Action". I can update both these fields no problem and the data base it updating correctly. My problem is,,,, When I select the "Result" - I need 2 things to happen.

1) Set another field called "SampleType" - this is a value based from 0 to 3 depending on which "Result" is selected - so basically I need to use a select/case check the "result"
2) once Sample Type is done I need to do some maths and update a field called "totalRisk" using the value in SampleType and three other fields.

The above is easy in MS Access. I'm sure it's sometihing I need to do on an **event ** such as **change ** on the "Result" select- but I'm not sure how to move forward on this.

If anyone has an idea I would greatly appreciate it.

Thank you in advance for any guidance

Extending base datatables features

$
0
0

Hello,

I would like to extend datatable behaviour by adding some code to initialization stage. I'm using this behavioru iniside multiple projects, so i would like to do this in "extension manner" (in separate .js file).

How to bind to "initialize" event so that my code would be called for every instance of datatable? During script processing none of the instance will exists so where to bind? Is there any "global" handle that i can bind to?

Filters after refresh

$
0
0

Hello,
How can I keep my filters the same after refreshing

Database Relations displayed in columns

$
0
0

Can anybody tell me how I can display database-relations in data wich is feteched from one table?

Thank you

How this should be done?

$
0
0

I am getting my data from database. The issue is I want to apply click function to button which is created by render in angular 6.

private SabhaList2() {
$(".content-wrapper").addClass("pt-0");
let exampleId2: any = $('#sabhaList');
this.tableWidget2 = exampleId2.DataTable({
select: false,
orderCellsTop: true,
dom: 'Bfrtip',
destroy: true,
colReorder: true,
fixedHeader: {
header: true,
},
scrollY: '90vh',
scrollX: '100wv',
bInfo: false,
bFilter: false,
paging: false,
buttons: [
],
data: this.tableData,
"columns": [
{ title: this.keys[0],data: this.keys[0] },
{ title: this.keys[1],data: this.keys[1] },
{ title: this.keys[2],data: this.keys[2] },
{ title: this.keys[3],data: this.keys[3] },
{ title: this.keys[4],data: this.keys[4] },
{ title: this.keys[5],data: this.keys[5] },
{ title: this.keys[6],data: this.keys[6] },
{ title: this.keys[7],data: this.keys[7] },
{ title: this.keys[8],data: this.keys[8] },
{ title: this.keys[9],data: this.keys[9] },
{ title: this.keys[10],data: this.keys[10] },
{ title: this.keys[11],data: this.keys[11] },
{ title: this.keys[12],data: this.keys[12] },
],
columnDefs: [{
'targets': 0,
'searchable': false,
'orderable': false,
'className': 'custom-checkbox',
'render': function (data, type, full, meta) {
return '<input type="checkbox" onchange ="inlineidgroup(' + data + ')" id="' + data + '" name="' + data + '" class="select-checkbox" value="' + $('<div/>').text(data).html() + '"> <button type="button" onclick="inlineidgroup('+data+')">Show Id</button>';
}
}],
});
}

I am storing my data and its keys in 2 different arrays named "tableData" and "keys" respectively. The Change and Click function is not working.

I receive an error saying:
Uncaught ReferenceError: inlineidgroup is not defined
at HTMLButtonElement.onclick (Attendance:1)

they are not able to find the below function:

inlineidgroup(data) {
console.log(data);
}

deferRender not working?

$
0
0

I have a very large table that takes 10's of thousands of rows from a sql server. At the moment I have to severely limit the amount of data being loaded, otherwise the table takes ages to load. My understanding is that deferRender should help fix this issue, however it doesn't appear to be doing anything. This is my code, thanks!:

$(function () {
    WtmHomePage.initialise();
});

var WtmHomePage =
{
    vars: {
    },
    fn: {
        ajaxPost: function (sFunction, onSuccess, onError, data, passThroughData, iTimeoutMillis) {

            if (typeof iTimeoutMillis !== "number") {
                iTimeoutMillis = 30000;
            }
            if (typeof passThroughData === "undefined") {
                passThroughData = {};
            }
            if (typeof onSuccess !== "function") {
                onSuccess = function () { };
            }
            if (typeof onError !== "function") {
                onError = function () { };
            }
            if (typeof data === "undefined") {
                data = null;
            }

            var sCsrfToken = $("input[name='__RequestVerificationToken']").val();
            if (typeof sCsrfToken !== "string") {
                sCsrfToken = "";
            }

            // Make ajax call
            $.ajax({
                type: "POST",
                url: "../Home/" + sFunction,
                contentType: "application/json; charset=utf-8",
                processData: false,
                dataType: "json",
                headers: { "X-XSRF-Token": sCsrfToken },
                data: data === null ? null : JSON.stringify(data),
                success: function (response, status, jqXhr) {
                    // Only send the data back because we dont want to handle two separate
                    // data layouts. This fails horribly if someone names a variable "d".
                    if (typeof response.d !== "undefined") {
                        onSuccess(response.d, status, jqXhr, passThroughData);

                    } else {
                        onSuccess(response, status, jqXhr, passThroughData);
                    }
                },
                error: function (jqXhr, status, errorName) {
                    // Handle generic errors if they exist, otherwise forward to error handler

                    if (jqXhr.status === 401) {
                        // Unauthorised. Force a refresh
                        window.location.href = window.location.href;
                        return;
                    }
                    else if (status === "timeout") {
                        // Function call timeout
                    }

                    onError(jqXhr, status, errorName, passThroughData);
                },
                timeout: iTimeoutMillis
            });
        },

        //mynewFunction: function () {
        //}
    },

    initialise: function (data) {
        WtmHomePage.fn.ajaxPost("GetTaskLog",
            function (data, status, jgXhr, params) {

                //INIT CHILD TABLE
                $('#WTM_LOG').dataTable({
                    "deferRender": true,

                    //HIDE PAGINATION IF PAGES <= 1
                    "fnDrawCallback": function (oSettings) {
                        if (oSettings._iDisplayLength > oSettings.fnRecordsDisplay()) {
                            $(oSettings.nTableWrapper).find('.dataTables_paginate').hide();
                        }
                        else {
                            $(oSettings.nTableWrapper).find('.dataTables_paginate').show();
                        }
                    },

                    "autoWidth": false,
                    "dom": "rtp",
                    "order": [[0, "desc"]],
                    "pageLength": 20,
                    "processing": true,
                    "data": JSON.parse(data),
                    "selector": ":not(:first-child)",
                    "sPaginationType": "simple_numbers",
                    "language": {
                        "paginate": {
                            previous: "<",
                            next: ">",
                        }
                    },
                    "columns": [
                        {
                            "data": "TaskSchedulerLogUid",
                            "visible": false
                        },
                        {
                            "data": "TaskName",
                            "visible": false
                        },
                        {
                            "data": "StartDate",
                            "render": function (data, type, row) {
                                var dateSplit = data.split("");
                                if (type === "display") {
                                    return dateSplit[8] + dateSplit[9] + '/' + dateSplit[5] + dateSplit[6] + '/' + dateSplit[0] + dateSplit[1] + dateSplit[2] + dateSplit[3] + " " + dateSplit[11] + dateSplit[12] + ":" + dateSplit[14] + dateSplit[15] + ":" + dateSplit[17] + dateSplit[18];
                                }
                                return data;
                            },
                        },
                        {
                            "data": "EndDate",
                            "render": function (data, type, row) {
                                var dateSplit = data.split("");
                                if (type === "display") {
                                    return dateSplit[8] + dateSplit[9] + '/' + dateSplit[5] + dateSplit[6] + '/' + dateSplit[0] + dateSplit[1] + dateSplit[2] + dateSplit[3] + " " + dateSplit[11] + dateSplit[12] + ":" + dateSplit[14] + dateSplit[15] + ":" + dateSplit[17] + dateSplit[18];
                                }
                                return data;
                            },
                        },
                        {
                            "data": "ErrorCount",
                            "render": function (data, type, row) {
                                if (type === 'display') {
                                    return (data === 0)
                                        ? data = '<span data-search="0"></span>'
                                        : data = '<a href="http://localhost/WTM/LogError/Index?id=' + row.TaskSchedulerLogUid + '" type="hidden" class="fas fa-exclamation-triangle" style="color:red"></a>';
                                }
                                return data;
                            },
                        },
                        {
                            "data": "EventCount",
                            "render": function (data, type, row) {
                                return (data > 0)
                                    ? data = '<a href="http://localhost/WTM/Details/Index?id=' + row.TaskSchedulerLogUid + '" type="hidden" class="fas fa-list" style="color:blue"></a>'
                                    : data = '';
                            },
                        },
                    ],
                    columnDefs: [
                        {
                            targets: 2
                        }
                    ]
                });

            },
            function (jqXhr, status, errorName, params) {
                alert("Child Table Error")
            },
            null,
            null,
            30000);
    }
}

Filter in header not working for fixed columns

$
0
0

I have a filter header with select elements but when the column is using the fixedColumn extension, the filter won,t work.

Here is a test case: http://live.datatables.net/jibaqoje/1/edit

If you filter on the Position (not fixed), it works but it doesn't work on the name column (fixed)


WCAG Compliance

$
0
0

Hi all,

I know I'm asking a question as a dicussion, but compliance is becoming more and more of an issue these days with trolling lawsuits so I thought discussion was more appropriate.

I'm getting this out of SortSite and other WCAG scanners.
I've tried to find a solution and haven't been able to:

Data tables allow screen reader users to understand column and row relationships.Layout tables read cells as a series of unrelated paragraphs with no tabular structure.Without TH or ROLE, screen readers apply heuristics to decide whether a table is a layout table or data table.These heuristics vary greatly between screen readers, and are affected by browser being used, window size,and font size (so the outcome is very unpredictable without TH or ROLE).If a data table has headers marked up using TD, then change these to TH.If a data table has no headers, add TH elements describing each row and/or column.If the table is only used for layout add role='presentation' to the TABLE element.
Impact on users:

•JAWS Reading: Treats tables without TH and ROLE as layout tables if the table contains cells above or below certain pixel sizes. This measurement is affected by browser window size, browser font size, and the browser used.
•NVDA Reading: Applies a 'layout table' heuristic to tables without TH and ROLE which varies depending on the browser used and on the window size in some circumstances.
•VoiceOver Safari OSX 10.9 Reading: Uses a sophisticated heuristic on tables without TH and ROLE, which is similar (but not identical) to the heuristic used by NVDA with Firefox.

Here's an example of the ouput:

        <table id="tablepress-16" class="tablepress tablepress-id-16">
        <thead>
        <tr class="row-1 odd">
            <th class="column-1">Costs</th><th class="column-2"><b>Cost of Attendance (On-Campus)</b></th><th class="column-3"><b>Cost of Attendance (Off-Campus)</b></th>
        </tr>
        </thead>
        <tbody class="row-hover">
        <tr class="row-2 even">
            <td class="column-1">Tuition</td><td class="column-2">$32,742</td><td class="column-3">$32,742</td>
        </tr>
        <tr class="row-3 odd">
            <td class="column-1">Student Housing</td><td class="column-2">$15,600</td><td class="column-3"></td>
        </tr>
        <tr class="row-4 even">
            <td class="column-1"><b>TOTAL</b></td><td class="column-2"><b>$48,342</b></td><td class="column-3"><b>$32,742</b></td>
        </tr>
        </tbody>
        </table>

What are recommendations here? Is this a "real" issue, or just a problem with a compliance engine false positive?

Or, how can I add TH or ROLE? I can't seem to find anything in the docs.

TIA!

Bug Fix for columns.adjust()

$
0
0

There is a bug in the columns.adjust() function that can cause columns to extend past the scroll bar (if using scrollY) or past the right edge of the table in some cases. This behavior will happen when using the style table-layout: fixed, allowing table cells to shrink smaller than the text they contain, and setting a column width to 0%. I have created a JS Bin showing the behavior as well as the reason it happens: live.datatables.net/rumomuze/1/edit. The reason being that setting the width of a th to 0% has a different behavior than setting the width to 0px. When the cell is set to 0px it will still be rendered, consuming an amount of space determined by it's padding, margin and border. However, when the cell is set to 0% padding, margin and border are ignored and the column is not rendered at all.

The culprit of this bug is the function _fnCalculateColumnWidths. In this function the datatable DOM instance is cloned and the columns of the cloned table are set to the column property sWidthOrig. If one of the columns sWidthOrig is 0% the cloned table's column is set to 0%, then the original table columns are calculated in px from that. This means that the px width for the other columns (those that aren't 0% width) are calculated with the 0% column not being rendered. When the calculated widths are applied to the original table the 0% column is set to 0px and suddenly has some width that didn't exist when the other columns were calculated, thus the original table is now larger than expected and extends beyond it's right boundary. The fix I am using for this involves calculating a sum of the padding, margin and border for any columns that are set to 0% and removing this space from the size of the cloned table. See the excerpt below:

/**
* Calculate the width of columns for the table
*  @param {object} oSettings dataTables settings object
*  @memberof DataTable#oApi
*/
function _fnCalculateColumnWidths ( oSettings )
{

...

// Apply custom sizing to the cloned header
headerCells = _fnGetUniqueThs(oSettings, tmpTable.find('thead')[0]);

var hiddenWidth= 0;
for (i = 0; i < visibleColumns.length; i++) {
    column = columns[visibleColumns[i]];
    if (/^0*\.?0*%$/.test(column.sWidthOrig)) {
        var header = $(column.nTh);
        hiddenWidth += header.width() === 0 ? header.outerWidth() :
            (header.css("padding-left") + header.css("padding-right") + header.css("margin-left") +
             header.css("margin-right") + header.css("border-left-width") + header.css("border-right-width"));
    }
    headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
        _fnStringToCss(column.sWidthOrig) :
        '';

...

// When scrolling (X or Y) we want to set the width of the table as 
// appropriate. However, when not scrolling leave the table width as it
// is. This results in slightly different, but I think correct behaviour
if (scrollX && scrollXInner) {
    tmpTable.width(scrollXInner);
}
else if (scrollX) {
    tmpTable.css('width', 'auto');
    tmpTable.removeAttr('width');

    // If there is no width attribute or style, then allow the table to
    // collapse
    if (tmpTable.width() < tableContainer.clientWidth && tableWidthAttr) {
        tmpTable.width(tableContainer.clientWidth);
    }
}
else if (scrollY) {
    tmpTable.width(tableContainer.clientWidth);
}
else if (tableWidthAttr) {
    tmpTable.width(tableWidthAttr);
}

//Remove width that was displaced by columns with 0% width
tmpTable.width(tmpTable.width() - hiddenWidth);

...

}

DataTables suddenly stopped working today

How can I stop header from sorting when custom dropdown is clicked?

$
0
0

I've put a custom dropdown in the headers of some of my datatables using Bootstrap Multiselect. I've also made the tables sortable. This is what it looks like:

The problem I'm having is that when I click the dropdown, the table also sorts. I only want the table to sort when I click the header, but not the dropdown button. The only place I've found a similar issue is here. However, this will not work, because it causes the dropdown not to appear.

NaN columnDefs

$
0
0

Hi, can somebody tell what I'm missing/doing wrong with the following code? The result in the front end is NaN being displayed rather than the desired result. Seem to be going round in circles trying to see what's wrong I'm sure somebody will spot it straight away and it's me being a bit slow!

{
                    targets: ['each_cost_price'],
                    render: function(data, type, row, meta) {
                        if (row['cost'] && row['unit'] && row['exrate'] !== null && data == null) {
                            return (row['cost'] / row['exrate'] / row['unit']).toFixed(2);
                        } else {
                            return (data == null) ? "" : "£" + data;
                        }
                    }
                }

Datatable doesn't work with multitables?

$
0
0

My issue here is that the variable of the second and third table don't keep the value of datable but the first one do it well. Anybody knows if datatable is able to handle more than one table at the same time. I post my code below:

        $(document).ready(function() {
            var table = $('#listasocios').DataTable();

            $('#listasocios tbody').on('click', 'tr', function () {
                if ( $(this).hasClass('selected') ) {
                    $(this).removeClass('selected');
                }
                else {
                    table.$('tr.selected').removeClass('selected');
                    $(this).addClass('selected');
                }
                //alert(table + ", " + JSON.stringify(table));
                var renglon = table.row( this ).data();
                var detalle = $("#detalle-table").DataTable({
                    "ajax": {
                        url: "ajax/cargar_reportedetalle",
                        type: "POST",
                        data: {
                            "idsocio": renglon[0]
                        },
                        dataSrc: ""
                    },
                    columns: [
                        { data: "contador" },
                        { data: "noeconomico" },
                        { data: "marca" },
                        { data: "modelo" },
                        { data: "placas" },
                        { data: "tipounidad" },
                        { data: "socio" },
                        { data: "km" },
                        { data: "estatus" },
                        { data: "serie"}
                    ],
                    columnDefs: [
                        { className: "cssbold text-center", targets: [0] },
                        { className: "text-center", targets: "_all" }
                    ],
                    dom: 'Bfrtip',
                    buttons: [
                        'colvis',
                        'excel',
                        'print'
                    ],
                    "autoWidth": false
                });
                //alert(detalle + ", " + JSON.stringify(detalle));
                var resumen = $("#resumen-table").DataTable({
                    "ajax":{
                        url: "ajax/cargar_reporteresumen",
                        type: "POST",
                        data: {
                            "idsocio": renglon[0]
                        },
                        dataSrc: ""
                    },
                    columns: [                            
                        { data: "unidad" },
                        {
                            "className":      'details-control',
                            "orderable":      false,
                            "data":           null,
                            "defaultContent": ''
                        },
                        { data: "marca" },
                        { data: "detenidos" },
                        { data: "activos" },
                        { data: "porparar" },
                        { data: "accidentados" },
                        { data: "cantidad"}
                    ],
                    columnDefs: [
                        { className: "text-center", targets: "_all" }
                    ],
                    dom: 'Bfrtip',
                    buttons: [
                        'colvis',
                        'excel',
                        'print'
                    ],
                    paging: false,
                    info: false,
                    order: [[1, 'asc']]
                });
                //alert(detalle + ", " + JSON.stringify(detalle));
                $("#reportes").modal("show");
            });

            $('#detalle-table tbody').on('click', 'tr', function () {
                alert("You have clicked here!!");
            });

            $('#resumen-table tbody').on('click', 'td.details-control', function () {
                alert("You have clicked here!!");                    
            });
        });

As you can see when I click one row of the second of third table it never trigger the alert inside.
Even when I try to get the variable value with an alert it's shown as undefined, or just crash: alert(detalle); or alert(detalle + ", " + JSON.stringify(detalle));

select field options remote data

$
0
0

Is there a current example of how to populate the select options from a returned query dataset?

fields: [ 
             {
                 label: "Home State:",
                 name: "HOMESTATE",
                 type: "select",
                 options: ["NC", "SC", "VA"]
              }

AutoFill and KeyTable with Dynamically Generated tables

$
0
0

Hey guys I am currently working on a project using datatables. I am currently using CreateElement('table') , using .innerHTML to add the </tds> and </trs> then using appendchild to add my table to the dom. My static tables all work fine, these tables do not use the editor and to include the autofill and keytable feature i just need to add {'keys': true, 'autoFill': true} in the properties when initializing the table. However in my Dynamically created tables the two extensions doesn't seem to be working at all, its as if the extensions are not even included. Dynamically generated tables are using the editor. I tried the datatable dubugger but it appears to get stuck when loading the version or uploading the configuration data.

Form my understanding when I am using the editor with datatables I need to add

   autoFill: {
        columns: ':not(:first-child)',
        editor:  editor
    },
    keys: {
        columns: ':not(:first-child)',
        editor:  editor
    },
    select: {
        style:    'os',
        selector: 'td:first-child',
        blurable: true
    },

to my properties to include the features but its as if these lines are not even included at all.
Here is my source code for the initialization for the editor and table of doing this.

    var editor = new $.fn.dataTable.Editor({
    table: '#seoScopeTable',
    /* THIS AJAX JUST CALCULATES THE TOTAL AND PUTS IT TO THE LAST COL*/
    ajax: function (a, b, data, successCallback, errorCallback) {
      var rowID = Object.keys(data.data)[0];
      var updatedData = data.data[rowID];
      updatedData['rowId'] = rowID;
      var excludeProps = ['', 'TOTAL'];
      var totalColData = 0;
      for (var eachDataCell in updatedData) {
        if (excludeProps.includes(eachDataCell)) {
          continue;
        }
        var parsedNumber = parseInt(updatedData[eachDataCell]);
        totalColData += parsedNumber ? parsedNumber : 0;
      }
      updatedData['TOTAL'] = totalColData;
      successCallback({
        'action': data.action,
        "data": [updatedData]
      });
    },
    'idSrc': 'rowId',
    fields: headers.map(function (val, index) {
      return {
        'name': val.split(' ').join().split(',').join('')
      }
    })
  })
  seoScopeTable = $(seoScopeTable).DataTable({
    'dom': "Bfrtip",
    'idSrc': 'rowId',
    'keys': {
      columns: ':not(:first-child)',
      editor: editor
    },
    'columns': headers.map(function (val, index) {
      return {
        'data': val.split(' ').join('').split(',').join('')
      }
    }),
    /*autoFill:{
      'columns': ':not(:first-child)',
      'editor': Teditor
    },*/
   'select': {
      'style':    'os',
      'selector': 'td:first-child',
      'blurable': true
    },
    'data': tableData,
    'ordering': false,
    'paging': false,
    'retrieve': true
  });

Do you guys see any problems with the initialization of the table and editor. Would you suggest anything where I should look to debug this problem?

Thanks

select2 as first field does not show focus

$
0
0

reference http://live.datatables.net/danosiyo/1/edit

I have a similar form in my application, with select2 as first field and date as 2nd field. I would like the first field to be focused, but don't see the easy way to do this. The calendar pop-up is a bit jarring when the form is displayed, and the user has to manually click on the first field.

I tried following suggestion in https://editor.datatables.net/reference/api/field().focus() comment to no avail. Not sure best way to put in form-options as you suggest. Shouldn't there be editor initialization option which defines focus? I think this is select2 anomaly because when I tried just type:'select' the focus defaulted to the first field as expected.

editor.on('open', function() {
    editor.field( 'position' ).focus();
});

How to hide all columns using buttons API ColVis

$
0
0

Hello,
I have colVis working and have managed to postfix a new button to the 'restoreVisibilty' button - i want my new button to hide all columns. The reason for this is my clients datatable has over 30 columns and hiding them individually is a real pain so he wants to be able to turn All off then simply select the ones he wants to make visible.. What code do i need to attach to the new button function to achieve this??

Many thanks in advance ...

How To Create Space Between Search Box & Table?

$
0
0

How to Put A Space Between the Search Box & Table? By Default At the Top It Says Show 10 Entries & Search. Just Want Some Space So The Search Box Isn't So Close to The Table???

how shall i do inline editing?

$
0
0

how to I do inline editing in our Datatable?

Viewing all 81387 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>