Add nested datatable within child row of another d

2019-05-30 06:10发布

问题:

I have seen where others have asked this question (like here: Add child row as nested datatable within exisiting datatable) but I have yet to see it answered.

I have a "master" datatable that makes use of the child row feature. Here's the code that initializes the "master" datatable. (I'm including it just to be thorough, but everything here works perfect.)

var table = $('#members');

var oTable = table.dataTable({

    "language": {
        "aria": {
            "sortAscending": ": activate to sort column ascending",
            "sortDescending": ": activate to sort column descending"
        },
        "emptyTable": "No data available in table",
        "info": "Showing _START_ to _END_ of _TOTAL_ entries",
        "infoEmpty": "No entries found",
        "infoFiltered": "(filtered1 from _MAX_ total entries)",
        "lengthMenu": "_MENU_ entries",
        "search": "Search:",
        "zeroRecords": "Loading..."
    },
    "buttons": [],
    "columnDefs": [
        {className: 'control'},
        {orderable: false, targets: 0 }
    ],
    // setup responsive extension: http://datatables.net/extensions/responsive/
    "responsive": true,
    "order": [

        [1, 'asc']

    ],
    "order-column": false,
    "lengthMenu": [
        [5, 10, 15, 20, -1],
        [5, 10, 15, 20, "All"] // change per page values here
    ],
    // set the initial value
    "pageLength": 5,
    "dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", 
});

This next bit of code is located right after the above code and accomplishes 2 things: 1) It prevents multiple child rows from being opened at once (just a personal preference) and 2) Uses an AJAX call to populate the child row that was just toggled open.

 table.on('click', 'tr', function () {

        var id = $(this).attr('id');
        if($(this).hasClass('parent'))
        {
            table.$('tr.parent').not(this).find('td:first-child').trigger('click');

            var load_member_leads = $(this).next().find('td.child > ul > li span.dtr-data');
            //var load_member_leads = $('#test');

            $.ajax({
                url: base_url + 'process/load_member_leads',
                type: 'POST',
                data: {test:id},
                dataType: "html", 
                success: function(data){
                    console.log ("success");
                    load_member_leads.html(data);
                    formRepeater();
                    initTable1(id);
                },
                failure: function (data) {
                    console.log ("failed");
                }
            });
        }
    });

This portion of the code appears to be working well, but here is where it gets tricky. Within the returned AJAX data, I have an html table that I would like to initialize using the datatables plugin. Essentially what I'd have is a nested datatable within a child row of another "master" datatable. The problem is, everything works great until I try to initialize the datatable plugin on the nested table using:

  initTable1(id);

(Note: the id variable being passed is to prevent multiple tables with the same ids. You can see in the code below how it's appended to the datatable init call.) Once this function is called, everything in the child row disappears and is erased from the DOM. Just gone. And I have no idea why.

Here is the code within the initTable1() function that initializes the 2nd datatable:

 var table2 = $('#leads_' + id);

    var oTable2 = table2.dataTable({
        "language": {
            "aria": {
                "sortAscending": ": activate to sort column ascending",
                "sortDescending": ": activate to sort column descending"
            },
            "emptyTable": "No data available in table",
            "info": "Showing _START_ to _END_ of _TOTAL_ entries",
            "infoEmpty": "No entries found",
            "infoFiltered": "(filtered1 from _MAX_ total entries)",
            "lengthMenu": "_MENU_ entries",
            "search": "Search:",
            "zeroRecords": "No matching records found"
        },

        destroy: true,

        //setup buttons extentension: http://datatables.net/extensions/buttons/
        buttons: [],

        // setup responsive extension: http://datatables.net/extensions/responsive/
        responsive: {
            details: {
                type: 'column',
                target: -1
            }
        },
        "columnDefs": [ {
           className: 'control',
           orderable: false,
           targets:   -1
        } ],
        "order": [
            [0, 'asc']
        ],
        "ordering": false,
        "lengthMenu": [
            [5, 10, 15, 20, -1],
            [5, 10, 15, 20, "All"] // change per page values here
        ],
        // set the initial value
        "pageLength": 10,
        "dom": ""

    });

And for good measure, here is the code being fetched by the AJAX call. (Note the $test variable is the same as the id variable being passed to the initTable1 function)

 <table class="table table-striped table-bordered dt-responsive" width="100%" id="leads_<?php echo $test; ?>">
                            <thead>
                                <tr>
                                    <th class="all">Column 1</th>
                                    <th class="all">Column 2</th>
                                    <th class="all">Column 3e</th>
                                    <th class="all">Column 4</th>
                                    <th class="all">Column 5</th>
                                    <th class="all">Column 6</th>
                                    <th class="all">Column 7e</th>
                                    <th class="all">Column 8</th>
                                    <th class="none">Column 9</th>
                                    <th class="all">Column 10</th>
                                </tr>
                            </thead>
                            <tbody>
                            <!-- table rows populated here - this is currently hardcoded for testing -->
                            </tbody>
                        </table>

Here's what DOES work, which may shed some light as to what's actually causing the problem.

1) It works if I comment out the initTable1() function within the AJAX call...well everything but the initialization of the datatable plugin on the 2nd table. But the html populates where it should within the child row of the "master" datatable.

2) It works if I change where the AJAX data is being populated - specifically, it works outside of the "master" datatable. It not only populates where it should (note the commented out var load_member_leads that points to $('#test').), but it initializes datatables correctly as well.

It only seems to break if I both initialize datatables on the second table, and place said table in the child row of the "master" datatable. And by break, I mean completely disappear as if the AJAX call failed - which it isn't according to the console.log.

This problem is driving me crazy, what am I doing wrong? Any help is much appreciated!

回答1:

I feel kind of stupid after spending hours on this one issue, but it turns out I was using the responsive extension rather than the built in functionality with datatables. For anyone else running into this issue, just follow and modify the code as needed from the example here: https://datatables.net/examples/api/row_details.html