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

Hide identical cells on consecutive rows

$
0
0

[To move to "Feature requests"?]

Hi everyone,

I have failed finding this (basic?) feature documented anywhere, so I had to write some piece of code instead.

In my table, I wanted to hide the repeated content of similar consecutive rows, like so:
http://jsfiddle.net/bbLjzspf/10232/
It kinda looks like a RowGroup matter, but you can't do it simply with RowGroup.

This is the code I used, plugin-free:

  var myTable;
  var classHidden = "transparent";

  myTable = $('#example').DataTable({
    data: dataSet,
    columns: columnDefs,
    fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
      var bHide = false;
      // _RD Ignore 1st row
      if (iDisplayIndex > 0) {
        // _RD If current data and previously stored data have the same number of cells (should always be the case?)
        if (aData.length == prevData.length) {
          // _RD Compare a given column
          var columnChecked = 0;
          var oldOffice = prevData[columnChecked];
          var newOffice = aData[columnChecked];
          // _RD If the rows match
          if (oldOffice == newOffice) {
            // _RD Tells the row data should be hidden
            bHide = true;
          }
        }
      }
      // _RD Cell(s) to hide or unhide
      var FirstCellToHide = 0;
      var nbOfCellsToHide = 1;
      var cellsToHide = $("td", nRow).slice(FirstCellToHide, nbOfCellsToHide - FirstCellToHide);
      // _RD If the rows should be hidden
      if (bHide) {
        // _RD Hide the cells (Note: "display: none" and "visibility: hidden" don't perform as expected)
        cellsToHide.addClass(classHidden);
      } else {
        // _RD Display the cells back
        cellsToHide.removeClass(classHidden);
      }
      // _RD Save the data from the current row
      prevData = aData;
      // _RD Return the treated row
      return nRow;
    }
  });
<style type="text-css">
    .transparent {
      color: transparent;
    }
</style>

Maybe someone else will have the time to implement this feature?

Various options I can think of:
* N°s of the columns (visible or not) to compare rows from
* N°s of the columns to hide when row has been found similar
* OR: One-line default option : "starting from the left, hide all similar columns over consecutive rows"
* Way to hide the repeated cells: transparent text (default), transparent cell including border, hidden cell, partially lowered opacity ...
* Other styling: remove borders inside a so-called "row group", unify the background color, add separation borders.

Thus, one could easily generate ligthened tables like that one:


Hide identical cells on consecutive rows

$
0
0

[sorry I couldn't post in "Feature requests" section], you can delete this

Problems with NOWRAP and child row with when I enable responsive table

$
0
0

I have added child rows from the example https://datatables.net/examples/api/row_details.html . Now I want to add responsive to the table. I have a problem that when I show the child row, the table is way to wide even for the container. I thought maybe there was some configuration problem but notice that when I remove "nowrap" from the table it is fine. But then the responsive does not work. When I have table class="display responsive nowrap" any long text in a TD in child row breaks the width. Is there a way to fix this?
Here is closed: https://www.screencast.com/t/OQrJtrus3Bc
Here it is opened: https://www.screencast.com/t/WOMclzely

cell.edit() - Cannot read property 'inline' of undefined

$
0
0

Hello,

I have this datatable:

$(document).ready(function () {
                
                SmixTable = table.DataTable({
                   ajax: {
                        url: "Services/ServiceClass.svc/GetMethod",
                        contentType: 'application/json; charset=utf-8',
                        data: { MixplanId: mId, SegmentId: sId },
                        dataType: 'json',                      
                    },
                  columns: [
                        { "data": "xx"  },
                        { "data": 'xx' },
                        { "data": 'xx' },
                        { "data": 'xx' },
                        { "data": 'xx' },
                        { "data": 'xx' },
                        { "data": 'xx' },
                        { "data": 'xx' },
                        { "data": "xx"},
                    ],

             });

            $('#smixOneTable').on( 'click', 'tbody td', function () {
                    SmixTable.cell( this ).edit();
                 } );
};

Im getting the error i mention in the title when pressing a cell in the table " Cannot read property 'inline' of undefined".

It is possible to use cell.edit() on a datatable? Or do I need to rewrite my table to use editor instead?. Don't know if its worth mentioning but the page contains 6 tables all have different id EG smixOneTable, smixTwoTable etc. but they have the same class name.

Atm im using all js and css files for editor extension just to be sure thats not the problem.

Any idea why I am receiving the error?

rowReorder.disable() not working as it should

$
0
0

Hi. I'm facing a strange issue on my dataTable. I've implemented a rowReorder function (including event) and this is working perfectly fine except one scenario. When I click a column to enable the sorting I want to disable to rowReorder if the column is not the Order column, and for this I have an event set for 'th' and this is also working perfeclty fine. So for example if I click on the column Name to sort the table by this column then the rowReorder (drag and drop) is disabled, and if i click the Order column to sort the table by this column then the rowReorder is enabled and its working fine. My issue is when I click the Name column header to sort the table by Name to disable the rowReorder function and I refresh the page, even if Im checking for what column has sorting enabled my rowReorder is always enabled event thought I'm calling the rowReorder.disable(). Below is code for my dataTable. Please help

$(document).ready(function () {

    var dataTable = $("table.reorder-table").DataTable({
            language: GetLanguage(),
            lengthMenu: [[10, 25, 50, 100, 250, 500, 1000], [10, 25, 50, 100, 250, 500, 1000]],
            serverSide: true,
            processing: true,
            stateSave: true,
            ajax: {
                url: GetDataRequestUrl(),
                type: "POST",
                datatype: "json",
                error: function (xhr, errorType, exception) {
                    $("table.reorder-table tbody").html("");
                    $("table.reorder-table")
                        .append(
                            '<tbody><tr class="odd"><td colspan="100%" class="dataTables_empty" valign="top">No data</td></tr></tbody>');
                    $("div.dataTables_processing").hide();
                }
            },
            columns: GetColumnDefinitions(),
            rowReorder: {
                selector: "td:not(:last-child)",
                dataSrc: "Order",
                update: false
            }
        });

        CreateRowReorderEvent(dataTable);

        dataTable.on("click",
            "th",
            function () {
                // if the column header clicked is Order then enable the rowReorder
                if (dataTable.column(this).index() === 0) {
                    dataTable.rowReorder.enable(); // <-- working like it should
                }
                else {
                    dataTable.rowReorder.disable(); // <-- working like it should
                }
            });

        //  below is called after page is reloded (refreshed) but its not disabling the rowReorder function 
        var order = dataTable.order();
        var colIndex = order[0][0]; // <-- get the index of the column where the sorting is applied

        if (colIndex === 0) { // <-- if the column is Order column 
            dataTable.rowReorder.enable();
        } else {
            dataTable.rowReorder.disable(); // <-- this is called but not working
        }
});

nested table

$
0
0

Hello everybody. I am learning also using this plugin. who can take me any example to use it with custom nested table. how can i to get access to nested table

Is it possible to overwrite responsivePriority ?

$
0
0

Hello,

I would like to ask if anyone knows how to overwrite the responsivePriority order hiding a column that has no data?

Example :

[
{ responsivePriority: 1, targets: 0 },
{ responsivePriority: 2, targets: 1 },
{ responsivePriority: 3, targets: 2 },
{ responsivePriority: 4, targets: 3 } ]

Let say that I want the above order but if target 2 has no data, I want it to be hidden.

Thanks in advance.

datatables create filter checkbox

$
0
0

Hello,
I found this on another site. With this example that perfectly corresponds to what I want to do.
Except that it works with 1 choice but no more and I would like to be able to check more checkboxes.

It's a little complex for my level, if someone could help me. I am a big user of datable but the.... I dry up in understanding
Thank you.

http://jsfiddle.net/vol7ron/z7wJ5/


Table width

$
0
0

Hi, Totally noob to data tables and am struggling. I'm creating a couple of tables at 48% width within a container. One table on the left of the page, the other on the right. Starts off great when page loads. I've only got the left table at present, loaded with the example data. The moment I click the table heading to sort the data, the table immediately expands to 100% of the container width. I added
'''$("#basic").on("column-sizing.dt",function(e,settings){
console.log( 'Column width recalculated in table');
}); '''
to see if something triggers it but get no console output. Can someone explain what I'm doing wrong?

Data table warning - Invalid Json response

$
0
0

I have a dropdown with 4 different item types including one to call all item types. When i call for each item type, I do not get any error alert and gets my table but when i do all item types i get that invalid JSON alert warning. There are 1078 rows and receiving when i check in debugger tools. Is there a way to bind this objects(data) I am getting to any variable so that i could check them. If so then how?

Set Custom id for every cell

$
0
0

Hi,
I have a table ("subscriptions") with the list of user subscribed to a site; I have attached to this table some columns: the number is dynamic.
The values of this colums ara taken from another table, where I have the id of the columns and the value (and the row id as primary key). So, any cells in the rendered table have a "custom" id, not the row id.
In the php controller, after the main sql to subscriptions table, I have a loop that add a column and for every row it search the correct value in the db: for 3 lines and 2 columns like below, I have the main sql and other 6 query.

How I can set, in the editor, the cell's id so when I edit the cell the controller can edit the correct value?

--------------------------------------------------------------------------
|| Id_row | Username |       Col_A      |       Col_B     | ....||
-------------------------------------------------------------------------
||  1        | Frank         | a (cell.id = 1) | b (cell.id = 2) | ...||
||  2        | Mario         | c (cell.id = 3) | d (cell.id = 4) | ...||
||  3        | Frank         | e (cell.id = 5) | e (cell.id = 6) | ...||
-------------------------------------------------------------------------

Thanks!
Roberto

(1046 No database selected )

$
0
0

i cann't connect to database and (I work with mysql only)

Use of “columnDefs” and “footerCallback” DATATABLE Ask Question

$
0
0

I need to know if I can combine the "footerCallback" with "columnDefs", because I want the "tfoot" to show me the total of each grouping

this is my code

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



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

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

                    // Total over all pages
                    total = api
                        .column(5)
                        .data()
                        .reduce(function (a, b) {
                            return intVal(a) + intVal(b);
                        }, 0);

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

                    // Update footer
                    $(api.column(5).footer()).html(
                       // '' + pageTotal + ' ( L' + total + ' total)'
                       '' + total.toFixed(2)
                    );
                },

                "columnDefs": [
                    { "visible": false, "targets": 2 }
                ],
                "order": [[2, 'asc']],
                "displayLength": 25,
                "drawCallback": function (settings) {
                    var api = this.api();
                    var rows = api.rows({ page: 'all' }).nodes();
                    var last = null;

                    // 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;
                    };

                    total = [];
                    api.column(2, { page: 'all' }).data().each(function (group, i) {
                        group_assoc = group.replace(' ', "_");
                        console.log(group_assoc);
                        if (typeof total[group_assoc] != 'undefined') {
                            total[group_assoc] = total[group_assoc] + intVal(api.column(5).data()[i]);
                        } else {
                            total[group_assoc] = intVal(api.column(5).data()[i]);
                        }
                        if (last !== group) {
                            $(rows).eq(i).before(
                                '<tr class="group"><td colspan="4">' + group + '</td><td class="' + group_assoc + '"></td></tr>'
                            );

                            last = group;
                        }
                    });
                    for (var key in total) {
                        $("." + key).html("L" + total[key].toFixed(2));
                    }


                }
            });


        });

I am currently projecting in this way:

I need something like this:

uncaught exception: Unable to automatically determine field from source.

$
0
0

Hopefully this will be a quick fix... hopefully

Full error I'm getting: "uncaught exception: Unable to automatically determine field from source. Please specify the field name"

I have a datatable with a field showing the concatenation of three fields, using the following:

   var table = $('#example').DataTable( {
      dom: "Bfrtip",
      ajax: "../server_side/scripts/ET_ASBresultsForBuilding.php?jobRef=P18-00053",
      iDisplayLength: 25,
      columns: [
         { data: null, render: function ( data, type, row ) {
                return data.tblASBassets.roomLocation;
            } },
         { data: null, render: function ( data, type, row ) {
                return data.tblASBassets.area + ', ' +data.tblASBassets.item + ', ' + data.tblASBassets.material;
            }, editField: null },

on the editor I've listed the three fields:

   editor = new $.fn.dataTable.Editor( {
      ajax: "../server_side/scripts/ET_ASBresultsForBuilding.php?jobRef=P18-00053",
      table: "#example",
      fields: [ { name: "tblASBassets.roomLocation", type: "display" },
                { name: "tblASBassets.area", type: "display" }, 
                { name: "tblASBassets.item", type: "display" }, 
                { name: "tblASBassets.material", type: "display" },

When I click on the datatable's field

I get the following

I know it's something to do with the editor trying to find the corresponding Editor Field - but because it's three fields in 1 I get the exception error.... all I want to do really is say - just show this at text - I don't want to edit it.

Anyone got any ideas? As ypou ca see I even tried setting the editfield parameter to null with no effect

Thank you in advance for any help given

Populate a text field by choosing an item from a select list?

$
0
0

So I have a user_id (Select field) and Full name (text field) in editor. I'm trying to populate the Full name based on the selected user_id.

{
                label: 'Assigned Employee ID:',
                name: 'user_id',
                type: 'select',
              }, {
                label: 'Assigned Employee Name:',
                name: 'assigned',
                type: 'text',
                readonly: true,
                fieldInfo: \"This field is read only and is created when the assigned employee id is selected.\",
                onChange: function ( data, type, set ) {
// get column indexes
// set data to assigned employee's full_name
                   return data.full_name;
                },
              }

I'm stuck trying to get the column index. Can anyone help? I read and re-read the columns().index() page but I'm just not getting it.


Flask AJAX Form Variable

$
0
0

I'm not able to retrieve the form variable in my flask app. Any thoughts?

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Datatables Example</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css"/>
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
  <script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
</head>
<body>

<form enctype="multipart/form-data" class="text-center border border-dark p-5">
    <p class="h4 mb-4">Info...</p>
    <input type="text" id="html_to_ajax_id" class="form-control mb-4" placeholder="Users Full Name">
    <button type="submit" class="btn btn-primary btn-block">Send</button>
</form>

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Extn.</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Extn.</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </tfoot>
</table>
<script>

$(document).ready(function () {

    $('#example').DataTable({
        "ajax": {

            "data" : {"form_data_to_flask" : $("#html_to_ajax_id").val() },
            "url": "/index_get_data",
            "dataSrc": "data",
            "type": 'POST',

            "contentType":"application/json"
        },
        "columns": [
            {"data": "name"},
            {"data": "position"},
            {"data": "office"},
            {"data": "extn"},
            {"data": "start_date"},
            {"data": "salary"}
        ]

    });
});

</script>
</body>
</html>

Flask:

from flask import Flask, render_template, jsonify, request

app = Flask(__name__)


@app.route('/')
def index():

    return render_template('index.html')


@app.route('/index_get_data', methods=['POST'])
def index_get_data_function():

    submitted = request.form['form_data_to_flask']

    print(submitted)

    data = {
    "data": [
      {
        "id": "1",
        "name": "John Q Public",
        "position": "System Architect",
        "salary": "$320,800",
        "start_date": "2011/04/25",
        "office": "Edinburgh",
        "extn": "5421"
      },
      {
        "id": "2",
        "name": "Larry Bird",
        "position": "Accountant",
        "salary": "$170,750",
        "start_date": "2011/07/25",
        "office": "Tokyo",
        "extn": "8422"
      }]
    }

    return jsonify(data)


if __name__ == '__main__':
    app.run(debug=True)

Error:

    raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'form_data_to_flask'

Nested tables from nested objects (JSON)

$
0
0

So, I tried a few of the available examples in the docs, but I couldn't advanced in the child rows section. I think I'm a bit confused with the concept of child rows/nested objects, where the docs show child rows as just an extension (more info) of the same object, that can be nested in the JSON response.

For my data, In summary, objects are documents and these documents may or may not have attached documents (it's simply an object with nested objects of the same type). Here it's a slice of the data:

            "codDoc": 1,
            "title": "Parent 1",
            "dateCreation": "1999-01-01T00:00:00",
            "childDocs": [
                {
                    "codDoc": 2,
                    "title": "Child of Parent 1",
                    "dateCreation": "1999-01-01T00:00:00",
                    "childDocs": null,
                    "parent": false
                },
                {
                    "codDoc": 3,
                    "title": "Child of Parent 2",
                    "dateCreation": "1999-01-06T00:00:00",
                    "childDocs": null,
                    "parent": false
                }
            ],
            "parent": true

The output should be a table that given the clicked element id (codDoc) I can show all attached documents of that parent.

De-duplicating entries from JS-sourced data

$
0
0

Context: I have a web worker that "subscribes" to data updates from the back end via a websocket, which are then published to a view rendered via DataTables.net To increase efficiency, added data is pushed down the websocket as a partial record (ie. one row only).

Since the data is decoupled from the DataTable (ie. it's not using the Ajax API; it's basically a JavaScript source), I cannot just add the row and render the table. In the event that two pushes of the same row are triggered, I end up with duplicate rows.

So, I whipped up a little plugin:

$.fn.dataTable.Api.register('deDupe', function (dataSet, idColumn) {
  idColumn = idColumn || 0;
  var columnData = this.columns().data()[idColumn];

  for(var i=0; i < dataSet.length; i++) {
    var thisId = dataSet[i].id;
    var matchedIndex = columnData.indexOf(thisId);
    if(matchedIndex > -1) {
      var matchedRow = $(this.rows().nodes()[matchedIndex]);
      this.row(matchedRow).remove();
    }
  }

  // return "this" for chaining
  return this;
});

(Don't laugh at me for taking comfort in old fashioned "for" loops!)

And then in usage, I do this:

myTable.deDupe(dataSet).rows.add(dataSet).draw();

The method that receives the data and then updates the table already has the incoming row, which is contained in "dataSet", and then I pass a COLUMN index for the column which is meant to contain the unique ID for de-duping purposes. Note that in code execution, rather than dropping an incoming duplicate, I am removing the previous row, then adding the incoming one. There are cases where the row contains updated data, and I really only care about de-duping at the ID level, not the contents level... always just blindly use the latest data.

So a few questions:

  1. Is there a better way of doing this? I would've loved to see a core option, but I didn't come across one. It seems like relatively common functionality. Am I crazy here, re-inventing the wheel? (in other words, an initialization option?)

  2. In the conditional checking if there's a match, you see this line: var matchedRow = $(this.rows().nodes()[matchedIndex]); This strikes me as wacky, but I couldn't get my head around the other ways of identifying a row to be used in the .remove() chain. In my mind, I already know the index of the row, so I thought something like matchedRow = this.rows(matchedIndex) would work, but I can't find that or something similar. So not only am I digging into rows().nodes() but then the whole thing is wrapped up in jQuery before then being passed into .row(matchedRow)'. It seems so heavily nested and wrapped for something I feel like I should already have direct access to.

Don't get me wrong; the code "works" and fixing it is probably a micro-optimization. But it strikes me as awfully convoluted and gives me some code smell, which I want to avoid for the sake of maintenance developers.

KeyTables: User Click On Non-Editable Fields Throws Error

$
0
0

I have an editor setup so that all of the fields in a row appear in the editor, but only the last one, the User Login Email, is actually user editable.
The user may open an editor dialog box, or edit the email address in-line.

I did this with:

                keys: {
                        columns:[6],    //UserLoginEmail, The only user editable field
                        editor:  editor,
                    },

I'm getting the interaction I want, but if the user double clicks on any of the inline non-editable field, I get this error in the console:

dataTables.keyTable.js:469 Uncaught TypeError: Cannot read property 'cell' of null

Is there any way to mitigate this?

Here are my key bits of code:

        editor = new $.fn.dataTable.Editor( {
                data: sampleDataStaff,
                table: "#example",
                fields: [ {
                        label: "ID",
                        name:  "id",
                        type: "hidden",
                        attr: {placeholder: 'ID'}
                     }, {
                        label: "UserStatus",
                        name:  "UserStatus"
                    }, {
                        label: "Group",
                        name:  "GroupName"
                    }, {
                        label: "User Name",
                        name:  "UserName",
                        attr:   {placeholder: 'No Name'}
                     },{
                        label: "Role Title",
                        name: "RoleTitle"   
                    }, {
                        label: "User Login Email",
                        name:  "UserLoginEmail",                
                    }, {
                        label: "Date",
                        name:  "Date",
                        type: "hidden",
                        //type:  "datetime"
                    }
                ],
            } );



            table = $('#example').DataTable( {
                dom: "Bfrtip",
                "paging": false,
                data: sampleDataStaff,

                columns: [
                    {
                      data: null,
                      defaultContent: '',
                      className: 'select-checkbox',
                       orderable: false
                    },
                    { name: "id",           data: "id",         orderable: false,   className: "columnDisabled",     visible: false},
                    { name: "UserStatus",   data: "UserStatus",     orderable: false,   className: "columnDisabled"},
                    { name: "GroupName",    data: "GroupName",      orderable: true,     className: "columnDisabled"},
                    { name: "UserName", data: "UserName",       orderable: false,   className: "columnDisabled"},
                    { name: "RoleTitle",        data: "RoleTitle",      orderable: false,   className: "columnDisabled"},
                    { name: "UserLoginEmail",   data: "UserLoginEmail", orderable: false},
                    { name: "Date",     data: "Date",           orderable: false,    className: "columnDisabled"     visible: false}
                ],

                "order": [ 7, 'desc' ],  //Order by Date

                columnDefs: [
                    {targets: 2,
                    fieldName: "UserStatus",
                     render: function (data) {
                         if (data == 'active') {
                             return('<div class="primaryDotBlack"></div>');
                         }else {
                             return('<div class="primaryDotGray"></div>');
                         }
                     }
                    }
                ],

                keys: {
                    columns:[6],    //UserLoginEmail, The only user editable field
                    editor:  editor,
                },

    ..... Button Stuff........
    ...... }); //End Of DataTable

One to Many

$
0
0

I am using the "Join tables - one-to-many join logic" on "https://editor.datatables.net/examples/advanced/joinArray.html", but I get the following error:

"DataTables warning: table id=mgmt - Join was performed on the field 'id' which was not included in the Editor field list. The join field must be included as a regular field in the Editor instance."

Using the same libraries. Wondering why the example works and mine does not

Viewing all 81384 articles
Browse latest View live


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