Re-open collapsed child rows after ajax.reload

Re-open collapsed child rows after ajax.reload

CodeStudent24CodeStudent24 Posts: 2Questions: 1Answers: 0

Hello,

I am trying to re-open my child rows when the table automatically reloads with the ajax.reload function of dataTable. (this will cause all the child rows to collapse)

But it seems like my child rows don't have ID's. How can I do this with the code below. I'm stuck on this for a few days now.
Hopefully someone can help me or point me in the right direction.

<script>
    var $tagsLabel = $("<lable>");
    var $tagsInput = $("<textarea>");

    /* Formatting function for row details - modify as you need */
    function format(d) {
        // `d` is the original data object for the row
        console.log(d);
        return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
            '<tr>' +
            '<td>Raw text:</td>' +
            '<td>' + d.Raw_html + '</td>' +
            '</tr>' +
            '</table>';
    }

    $(document).ready(function () {
            var detailRows = [];

            var dt = $("#dataTable")
                .on("preInit.dt", function (e, settings) {
                    $tagsLabel.append($tagsInput);
                    $('.dataTables_tags').append($tagsLabel)
                })
                .on("init.dt", function (e, settings) {
                    $tagsInput.tagEditor({
                        delimiter: ', ',
                        placeholder: 'Enter search keywords ...',
                        onChange: function (field, editor, tags) {
                            if (tags.length) {
                                if (tags.length > 1) {
                                    $table.search(tags.join('|'), true, false).draw();
                                } else {
                                    $table.search(tags[0]).draw();
                                }
                            } else {
                                $table.search('').draw(true);
                            }
                        },
                    });
                }).DataTable({
                    mark: true,
                    "searchHighlight": true,
                    "dom": '<l<"dataTables_tags"><t>ip>',
                    "ajax": '/json-int',
                    "columns":
                        [
                            {
                                "class": 'details-control',
                                "orderable": false,
                                "data": null,
                                "defaultContent": '',
                                width: "5px"
                            },
                            {"data": "Timestamp", width: "135px"},
                            {"data": "Title"},
                            {"data": "Url"},
                            {"data": "domain"},
                            {"data": "Type"},
                            {"data": "Raw_html", "visible": false}
                        ],
                    "order":
                        [[1, 'asc']],
                    "initComplete":

                        function () {
                            setInterval(function () {
                                dt.ajax.reload(null, false);

                                var currentdate = new Date();
                                var datetime = currentdate.getDay() + "/" + currentdate.getMonth()
                                    + "/" + currentdate.getFullYear() + " @ "
                                    + currentdate.getHours() + ":"
                                    + (currentdate.getMinutes() < 10 ? '0' : '') + currentdate.getMinutes() + ":" + currentdate.getSeconds();
                                document.getElementById("lastUpdated").innerHTML = "Last updated: " + datetime;
                            }, 5000);
                        }
                }).on('draw', function () {
                    $.each(detailRows, function (i, id) {
                        $('#' + id + ' td.details-control').trigger('click');
                    });
                });


            $('#dataTable tbody').on('click', 'tr td.details-control', function () {
                var tr = $(this).closest('tr');
                var row = dt.row(tr);
                var idx = $.inArray(tr.attr('id'), detailRows);
                
                if (row.child.isShown()) {
                    tr.removeClass('details');
                    row.child.hide();

                    // Remove from the 'open' array
                    detailRows.splice(idx, 1);
                } else {
                    tr.addClass('details');
                    row.child(format(row.data())).show();

                    // Add to the 'open' array
                    if (idx === -1) {
                        detailRows.push(tr.attr('id'));
                    }
                }
            });

            dt.on('draw', function () {
                $.each(detailRows, function (i, id) {
                    $('#' + id + ' td.details-control').trigger('click');
                });
            });
        }
    );
</script>

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,142Questions: 26Answers: 4,736
    Answer ✓

    To use an id you would need to generate a unique id for each shown child row. Can be easily done if each row has unique data. You would then add that id in the format function.

    I would take a different approach. I would use the rows() API to get each row with the class details each time you reload the Datatable. Then use those rows to show the child rows. Here is an example:
    http://live.datatables.net/qolevune/1/edit

    It uses rows().every() to iterate each shown child row. It uses rows().nodes() with to$() to add the details ('shown` in the example) class.

    Kevin

  • CodeStudent24CodeStudent24 Posts: 2Questions: 1Answers: 0

    @kthorngren Thank you. This worked for me.
    For anyone trying to implement this. This is my working code:

    <script>
        var $tagsLabel = $("<lable>");
        var $tagsInput = $("<textarea>");
    
        /* Formatting function for row details - modify as you need */
        function format(d) {
            // `d` is the original data object for the row
            return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
                '<tr>' +
                '<td>Raw text:</td>' +
                '<td>' + d.Raw_html + '</td>' +
                '</tr>' +
                '</table>';
        }
    
        $(document).ready(function () {
                var childRows = null;
    
                var dt = $("#dataTable")
                    .on("preInit.dt", function (e, settings) {
                        $tagsLabel.append($tagsInput);
                        $('.dataTables_tags').append($tagsLabel)
                    })
                    .on("init.dt", function (e, settings) {
                        $tagsInput.tagEditor({
                            delimiter: ', ',
                            placeholder: 'Enter search keywords ...',
                            onChange: function (field, editor, tags) {
                                if (tags.length) {
                                    if (tags.length > 1) {
                                        $table.search(tags.join('|'), true, false).draw();
                                    } else {
                                        $table.search(tags[0]).draw();
                                    }
                                } else {
                                    $table.search('').draw(true);
                                }
                            },
                        });
                    }).DataTable({
                        mark: true,
                        "searchHighlight": true,
                        "dom": '<l<"dataTables_tags"><t>ip>',
                        "ajax": '/json-int',
                        "columns": [
                            {
                                "class": 'details-control',
                                "orderable": false,
                                "data": null,
                                "defaultContent": '',
                                width: "5px"
                            },
                            {"data": "Timestamp", width: "135px"},
                            {"data": "Title"},
                            {"data": "Url"},
                            {"data": "domain"},
                            {"data": "Type"},
                            {"data": "Raw_html", "visible": false}
                        ],
                        "order": [[1, 'asc']],
                        "initComplete": function () {
                            setInterval(function () {
                                childRows = dt.rows($('.shown'));
                                dt.ajax.reload(null, false);
    
                                var currentdate = new Date();
                                var datetime = currentdate.getDay() + "/" + currentdate.getMonth()
                                    + "/" + currentdate.getFullYear() + " @ "
                                    + currentdate.getHours() + ":"
                                    + (currentdate.getMinutes() < 10 ? '0' : '') + currentdate.getMinutes() + ":" + currentdate.getSeconds();
                                document.getElementById("lastUpdated").innerHTML = "Last updated: " + datetime;
                            }, 5000);
                        }
                    });
    
    
                $('#dataTable tbody').on('click', 'tr td.details-control', function () {
                    var tr = $(this).closest('tr');
                    var row = dt.row(tr);
    
                    if (row.child.isShown()) {
                        // This row is already open - close it
                        row.child.hide();
                        tr.removeClass('shown');
                    } else {
                        //tr.addClass('details');
                        //row.child(format(row.data())).show();
                        // Open this row
                        d = row.data();
                        row.child(format(d)).show();
                        tr.addClass('shown');
                    }
                });
    
    
                dt.on('draw', function () {
                    // If reloading table then show previously shown rows
                    if (childRows) {
    
                        childRows.every(function (rowIdx, tableLoop, rowLoop) {
                            d = this.data();
                            this.child($(format(d))).show();
                            this.nodes().to$().addClass('shown');
                        });
    
                        // Reset childRows so loop is not executed each draw
                        childRows = null;
                    }
    
                });
            }
        );
    </script>
    
This discussion has been closed.