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

How to hidden columns without data?

$
0
0

Hello. I have a table with columns that do not show the data or do not bring anything. How can I hide the columns that are empty?

My table:

`const tableRanking = $("#sellersQuantityTable").DataTable({
responsive: true, "lengthChange": false, "autoWidth": false, "searching": true, fixedHeader: true, "scrollX": true,
buttons: [
{
extend: "excel",
title: '',
filename: 'Venta por Financiera',
exportOptions: { orthogonal: 'export' },

}],
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api();

// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
    return typeof i === 'string' ?
        i.replace(/[\$,]/g, '')*1 :
        typeof i === 'number' ?
            i : 0;
};

rendered = api
    .cells( null, 1, { page: 'total'} )
    .render('display')
    .reduce( function (a, b) {
        return intVal(a) + intVal(b);
    }, 0 );
    console.log(rendered)

pageTotal = api
    .column( 1, { page: 'current'} )
    .data()
    .reduce( function (a, b) {
        return intVal(a) + intVal(b);
    }, 0 );

// Update footer
$( api.column(1).footer() ).html(
  'TOTAL: '+pageTotal + '(' + rendered +')'
);

},

language: {
    "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Spanish.json"
},
columns: [
    { "data": "MarcaTotal" },
    {
        "data": "MontoMarca", render: function (data, type, row) {
            return type === 'export' ?
                data.replaceAll(/[$ |.]/g, '').replace(',', '.') :
                data;
        },
    },         
],

order: [[1, "desc"]],
rowsGroup: [0]

}); `

I checked the data of my api and they arrive correctly so that is not a problem


Swap a row and set a value update the whole row values

$
0
0

Hi,
Here is the method I'm using to move a row up or down in datatable :

// Move a row up or down
  moveRow(currentRow, direction) {
    var currentRowIndex = currentRow.index()
    if (direction === 'up') {
      if (currentRowIndex < 1) {
        return
      }
    } else {
      var rowCount = $(this.tableId).dataTable().fnGetData().length
      if (currentRowIndex + 1 === rowCount) {
        return
      }
    }
    const nextRow =
      direction === 'up'
        ? this.table.row(currentRowIndex - 1)
        : this.table.row(currentRowIndex + 1)
    const currentRowData = currentRow.data()
    const nextRowData = nextRow.data()
    currentRow.data(nextRowData).draw()
    nextRow.data(currentRowData).draw()
  }

But when I move a row up or down then update value to one of the moved row, the other take the same values on the whole row... I tried to comment my instruction on submit and edit but the problem persists so I think my problem comes from this moveRow() method.

Any ideas what I'm badly writing here?

Thank you for your support!

data range filter

$
0
0

i am using this as an example: https://datatables.net/extensions/datetime/examples/integration/datatables.html
I have 2 changes i need to make in that example, first how do i change the calendar that opens when you click the input to spanish language and what changes i need to make in the JS if in my example the datatable shows the date like this 13/01/2022, the example shows the format date like this 2022/01/13 and i having troubles with that

postEdit javascript event not firing

$
0
0

This my first attempt at an editor.
My code:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.11.4/js/dataTables.jqueryui.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.jqueryui.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/select/1.3.4/js/dataTables.select.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/datetime/1.1.1/js/dataTables.dateTime.min.js"></script>
<script type="text/javascript" language="javascript" src="js/dataTables.editor.min.js"></script>
<script type="text/javascript" language="javascript" src="js/editor.jqueryui.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/editor.jqueryui.min.css" />
<script>
var editor;
$(document).ready(function() {
  editor = new $.fn.dataTable.Editor( {
      ajax: "http://virtual-techno.co.uk/heating/timetable.php",
      table: "#timetable",
            idSrc:  'id',
      fields: [ {
              label: "Start period:",
              name: "pstart"
          }, {
              label: "End period:",
              name: "pend"
          }, {
              label: "Target:",
              name: "target"
                    }
                ]
            });
    
        // Activate an inline edit on click of a table cell
        $('#timetable').on('click','tbody td:not(:first-child)', function (e) {
            editor.inline( this );
        });
                
    var table=$('#timetable').DataTable( {
        ajax: {
            url: "http://virtual-techno.co.uk/heating/timetable.php",
                    type: "get",
                  dataSrc: 'timetable'
                },
                columns: [
                    {data: 'pstart'},
                    {data: 'pend'},
                    {data: 'target'}
                ],
        select: true
            });
        
        // Display the buttons
        new $.fn.dataTable.Buttons( table, [
            { extend: "create", editor: editor },
            { extend: "edit",   editor: editor },
            { extend: "remove", editor: editor }
        ] );
 
        table.buttons().container()
            .prependTo( $('div.fg-toolbar:eq(0)', table.table().container() ) );

            editor.on('postEdit', function (e, json, data, id) {
                    console.table(data);
            }); 
} );

</script>
</head>
<body>
<h1>Timetable</h1>
<table id="timetable">
    <thead>
        <tr>
            <th>Start</th>
            <th>End</th>
            <th>Target</th>
        </tr>
    </thead>
</table>
</body>
</html>

Error messages shown: none
Description of problem:
This creates an editor and shows me the incoming data.
I click a cell and the Edit button. A box appears and I change the data then click "Update".
The screen goes back to showing the original data and the postEdit event does not fire.

I looked for a complete simple example but did not find one.
Suggestions please.

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

fixedHeader stops working with Detail Rows

$
0
0

I just have a quick question. Not sure there's a real need for a test case.

I have turned on fixedHeader and it works just fine as long as I don't have too many detailed/child rows are not showing. I have functionality to expand all detail/child rows via a button (expands for the current page) or header row (expands all rows).

At any rate, let's say I have (100) rows and I expand each rows detail/child row. The fixedHeader works initially but if I scroll down far enough, the header eventually scrolls out of sight. But again, if all detail/child rows are collapsed, it doesn't seem to affect the header row. I tested with a few hundred rows and it stayed in place.

Just wondering if I missed a setting or not. I reviewed the examples, but none of them involved detail/child rows so I'm guessing it is not fully designed to work with detail/child rows.

Fyi, "freakin awesome stuff you guys have created! I love datatables and the customers using my app seem to love it to!

Search Panes layout not (really) responsive

$
0
0

Hello everyone,

I have a question regarding the layout of the SearchPanes.
Since I boosted a lot the rendering speed by caching the content, each pane is displayed with a full width when the page is loaded, which is ugly and not friendly at all. I had no problem before when the seeding of the table was slower, but now here is how it looks:

If is resize the window even so slightly, then it's displayed correctly with responsive rows of three to four panes. I know I can force the layout with searchPanes: { layout: 'columns-x' }, but in that case I lose the responsiveness that is quite important since my number of panes can change.

Do you have any insight?

Thanks!

How can I create filter in server side processing?

$
0
0

Hi,
I'm trying to create a filter in DataTables, but what I found is only filtering the data in "front end" (in the datatables script). I have 10K rows in the SQL table so I think, the "front end filtering/searching" is not my best option. I need to create a filter to my SQL Query in server-side, and get back only the filtered rows (datas).

Also the search option is not good option for me because I have in tables values like 1 or 2 (boolean).

My DataTables using this method (way) of fetching datas from SQL in backend:

include 'config.php';

/// Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value

$searchArray = array();

/// Search 
$searchQuery = " ";
if($searchValue != ''){
   $searchQuery = " AND (emp_name LIKE :emp_name or 
        email LIKE :email OR 
        city LIKE :city ) ";
   $searchArray = array( 
        'emp_name'=>"%$searchValue%", 
        'email'=>"%$searchValue%",
        'city'=>"%$searchValue%"
   );
}

/// Total number of records without filtering
$stmt = $conn->prepare("SELECT COUNT(*) AS allcount FROM employee ");
$stmt->execute();
$records = $stmt->fetch();
$totalRecords = $records['allcount'];

/// Total number of records with filtering
$stmt = $conn->prepare("SELECT COUNT(*) AS allcount FROM employee WHERE 1 ".$searchQuery);
$stmt->execute($searchArray);
$records = $stmt->fetch();
$totalRecordwithFilter = $records['allcount'];

/// Fetch records
$stmt = $conn->prepare("SELECT * FROM employee WHERE 1 ".$searchQuery." ORDER BY ".$columnName." ".$columnSortOrder." LIMIT :limit,:offset");

// Bind values
foreach($searchArray as $key=>$search){
   $stmt->bindValue(':'.$key, $search,PDO::PARAM_STR);
}

$stmt->bindValue(':limit', (int)$row, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int)$rowperpage, PDO::PARAM_INT);
$stmt->execute();
$empRecords = $stmt->fetchAll();

$data = array();

foreach($empRecords as $row){
   $data[] = array(
      "emp_name"=>$row['emp_name'],
      "email"=>$row['email'],
      "gender"=>$row['gender'],
      "salary"=>$row['salary'],
      "city"=>$row['city']
   );
}

/// Response
$response = array(
   "draw" => intval($draw),
   "iTotalRecords" => $totalRecords,
   "iTotalDisplayRecords" => $totalRecordwithFilter,
   "aaData" => $data
);

echo json_encode($response);

In this code as you can see I have Search option, but as I said I can't use it for filtering columns with boolean values.

Another example what I want to do:

I have a column named by "edited" with boolean values. How can I get/filter those rows where the column "edited" have values 0?

I'm using MariaDB.

Thank you for your help!


Modal on non-responsive table

$
0
0

Hi,

Using the responsive.details.display option, we are able to get a bootstrap modal for each row.

$(document).ready(function() {
$('#example').DataTable( {
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.modal( {
header: function ( row ) {
var data = row.data();
return 'Details for '+data[0]+' '+data[1];
}
} ),
renderer: $.fn.dataTable.Responsive.renderer.tableAll( {
tableClass: 'table'
} )
}
}
} );
} );

Is there a way to create a bootstrap modal for rows without making the table responsive?

Kind regards,
Steve C

How to compare datetime column cell by cell which one is latest date and perform some math

$
0
0

Hello, I have table which has column location and details of assets by location. I want to iterate location wise for each asset and check some datetime column - that which asset has latest/biggest date, and add 14 days in that biggest date.

For e.g. location Avenue has two asset > A1 , A2.. now I want to check from A1 and A2 which asset has latest date.. take that date and add 14 days in to it and store in another column.

so I tried render function in which I am not able to iterate using location column.

Please check below example - This is how I compare data.. column wise. here I am comparing two different columns using if else. But now I want to comapre data from same column (so row wise).

Please help if there are any function in datatables that I can use.

 { data: "TIDForecast",  

 render : function(data,type,row){

                 if((row.SIForecast == null) && (row.SIActual == null)){

                     return null;
                 }

                 var SIF = moment(row.SIForecast).add(98, 'days'); // Start Install Forecast
                 var SIA = moment(row.SIActual).add(98, 'days'); // Start Install Actual

                 // IF ACTUAL IS EMPTY USE FORECAST.
                 // IF ACTUAL IS NOT EMPTY USE ACTUAL.


                    if(row.SIActual == null)
                    {
                        return SIF.format('DD MMM YYYY'); // Add 98 Days into SIForecast Date
                    }


                    else( row.SIActual != null)
                    {
                        return SIA.format('DD MMM YYYY'); // Add 98 Days into SIActual Date
                    }


                }
}

Print / Copy / Excel doesn't print 'selected' option value

$
0
0

I am trying to print or copy a table which has 8 columns. I am having 2 issues
1. I am only able to print 7 of them the 8th one goes outside the page. If I reduce the size it becomes very small
2. The very last column is for status (select) and when I print it I see all 4 status being printed instead of just the selected value. NOTE: This selected class doesn't have the same name example <select name="status-2" id="status-2" class="status-select"> I add value ""id to each one of the row to get the option value from DB. You can take a look at **screenshot **for reference

Datetime formatted incorrectly when 'editing' a row

$
0
0

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

I have a table where I want the datetime format as YYYY-MM-DD HH:mm.

I've explicitly stated this in my code:

         { data: "tbl_mg_accounts.account_dt",         render: function (data, type, row) {
          return moment(new Date(data).toString()).format('YYYY-MM-DD HH:mm');
        } }

I have a button called 'duplicate', where I essentially select a row and the form keeps that data but I can edit it and resubmit as a new entry.

When I click this, the datetime format goes different, e.g. > Tue, 16 Nov 2021 09:30:00 GMT. This is despite specifying in my editor object:

                type:  'datetime',
                def:   function () { return new Date() },
                format: 'YYYY-MM-DD HH:mm'

When I click on that column when editing, and choose another datetime from the picker, the format corrects itself.
This same behaviour is for inline editing too.

How can I consistently have the same format throughout? The backend has YYYY-MM-DD HH:mm format so I'm not sure how Tue, 16 Nov 2021 09:30:00 GMT format appears. Is this a default of moment.js or from datatables side?

DataTable Editor not working for me

$
0
0

I have developed wp posts table using wp-rest-api and ajax on understrap child theme. It's working fine with dataTables. I just need to edit, delete each rows in the table using DataTable Editor. Could you please advice me that how to do it?

Changing the data limit when exporting to Exccel

$
0
0

Currently I'm using Datatable to fill up all my data in 10 rows each using pagination. For this I've mentioned in my model a length and start value like so:

$this->db->limit($length,$start);

Now I recently added the Datatable.buttons library for the export to excel functionality. So now I have added the following code to my AJAX call:

  dom: 'Bfrtip',
  buttons: [
          {
              extend: 'excelHtml5',
              exportOptions: {
                  columns: ':visible'
              }
          },
          'colvis',          
    ],

Now I can successfully export the data to an excel sheet, but it only exports the 10 entries that are shown in the respective pagination page. I want to be able to manually specify that I want to retrieve the first 1000 or 2000 rows

browser compatibility

$
0
0
function formatc ( table ) {
    // video hide compilations checkbox
    var state;
    if (table.state.loaded() === null) {
        state = '';
    } else {
        try {
            state = table.state.loaded()['columns'][COLUMN3]['search']['search'];
        } catch (error) {
            state = '';
        }
    }
    return '<input type="checkbox" id="covdcb" value="hide"'+
            (state === 'hide compilation' ? ' checked' : '')+
            '>Hide Compilations</input>';
}
$(document).ready(function() {
    var table = $('#covd').DataTable( {
        "processing": true,
        "serverSide": true,
        "dom": "<'tbh'l<'compilations'>f>rtip",
        'deferLoading': (coepvd === 'v' ? null : 0),
        "stateSave": true,
        "stateDuration": -1,
        "stateLoadParams": function (settings, data) {
            data.search.search = "";
            },
        "ajax": { "url": "/covd.php",
            "data": function (d) {
                d.CompanyID = companyID;
                }
            },
        "pagingType": "input",
        "order": [[COLUMN0, 'desc']],
        "search": { "return": true },
        "lengthMenu": [ 25, 50, 100 ]
    } );
    // recompute column widths on search
    table.on( 'search.dt', function () {
        table.columns.adjust();
    } );
    // recompute column widths on sort
    table.on( 'order.dt', function () {
        table.columns.adjust();
    } );
    $("div.compilations").html(formatc(table));
    $(document).ready(function() {
        $("#covdcb").change(function() {
            var table = $('#covd').DataTable();
            if ($(this).is(':checked')) {
                table.columns(COLUMN3).search('hide compilation').draw();
            } else {
                table.columns(COLUMN3).search('show compilation').draw();
            }
        });
    });
} );

I have users using unpredictable browsers that I can't test with.
One is using Safari 9 and can't get a search to work.
I use: "search": { "return": true }

Is there any experience with the enter key not working for a search on old browsers?
Catching an enter key seems rather rudimentary.
The user can see the Javascript errors and none show up.

Sorry, I can't share the website so I expect any help here will be pure luck.
I am a little worried that I may have gotten myself into a bind with older browsers.

I was going to experiment with removing the webkit search cancel but that was supported in Safari 3!

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


How to load server-side data in ASP.NET MVC ?

$
0
0

I'm trying to use server-side data loading to fill the table. My view is:


Controller code:

The result is:

The output Json which controller returns is:

What is wrong in my code?

Customize render callback to not expect a string and just perform actions within the callback fn

$
0
0

Link to test case:
https://github.com/DataTables/ColReorder/issues/49

Current versions of packages installed:
"datatables.net-dt": "^1.11.3",
"datatables.net-colreorder-bs4": "^1.5.5",

Description of problem:

In reorder of columns using ColReorder, it was unable to trigger the dynamic insertion of components done in createdCell callback due to render being run.

Hence, the workaround I found was to trigger the same createdCell callbackfn in the return of renderFn.

I have raised a PR for the same https://github.com/DataTables/DataTablesSrc/pull/198

The usage sample is as below

col.renderReturnType = 'function'; // only then will these changes be activated

const createdCellCallback = (tdElm, cellData, rowData, rowIndex) => {
  // dynamically insert an angular component into tdElm with help of Renderer2; passing in needed values from rowData and cellData as @Inputs to the component
}

col.render = (data, type, row, meta) => { return createdCellCallback; }

col.createdCell = createCellCallback;

Please check and merge this at the earliest, in a matter of hours to be exact.

all headers and columns to left

$
0
0

I have a table with 2 columns

how can i move everything to the left?

Server-side processing and SQL command timeout with .NET library

$
0
0

I'm using server-side processing and ajax request are handled with DataTables .NET library like:

var connection = ... // System.Data.Common.DbConnection
var db = new Database("azure", connection);
var response = new Editor(db, ...).Process(Request).Data();

There seems to be built-in 30 second CommandTimeout (not to be confused with ConnectionTimeout which is set in database connection string or Ajax request timeout set in client side).

I've crawled through all documentations but could not find a way to set timeout for the SQL command. Any help? Some of my requests in a multi-billion row data takes minute and we can live with that.

Error "dataTable.order() is not a function"

$
0
0

Note: I have seen that this question has been asked before, but the solution (one jQuery instead of multiple) doesn't help me sadly. I only include jQuery once, and the datatables.min.js and .min.css files are included after.

Whenever I order my table, it's supposed to log which order the user decided to choose. But, using this code right here:

dataTable = $("#hourTable").dataTable({
    language: {
        url: "frameworks/de_de.json",
        responsive: true
    }
});
$("#hourTable").on("order.dt", function(){
    var order = dataTable.order();
    console.log( 'Ordering on column '+order[0][0]+' ('+order[0][1]+')' );
});

does not work. The event does get triggered whenever I need it, but instead of the order chosen, I get the error dataTable.order() is not a function. I did try to print out the dataTable object, and this returns a big amount of functions, but not the one I'm looking for. Here's an example of what I get:


So, I guess it is working correctly? I'm not able to get the order of the table though. Is there something I'm doing wrong here?

Thanks in advance

Viewing all 82279 articles
Browse latest View live