Vasco Silva
Vasco Silva

Reputation: 51

Datatables - How can I hide details-control If no data to show

I want to disable details-control if no data exists to show.

function format(d) {   
    return d[1];
}

var table = $('#table').DataTable({
    "searching": false,
    "ordering": false,
    "info": false,
    dom: 'frt',
    serverSide: true,
    "pageLength": 4,
    language: {
        "zeroRecords": "..."
    },
    "stripeClasses": [],
    "columns": [
        null,
        null,
        null,
        null,
        {
            "class": "details-control",
            "orderable": false,
            "data": null,
            "defaultContent": ""
        },
        null
    ],
    ajax: $.fn.dataTable.pageLoadMore({
        url: "@Url.Action("Load")"
        }),
    drawCallback: function () {
            $('#btn-Load').toggle(this.api().page.hasMore());
        }
});

// Add event listener for opening and closing details
$('#table tbody').on('click', 'td.details-control', function () {
    var tr = $(this).closest('tr');
    var row = table.row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        // Open this row
        row.child(format(row.data())).show();
        tr.addClass('shown');
    }
});

HTML:

<table id="table" class="display" cellspacing="0">
    <thead>
        <tr>
            <th>@Html.LocalResources("A")</th>
            <th></th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

How can I hide the display icon if no data on position 1 to show? I consult this site: https://datatables.net/examples/api/row_details.html to view the api and how it works.

The DataTables API has a number of methods for attaching child rows to a parent row in the DataTable. This can be used to show additional information about a row, useful for cases where you wish to convey more information about a row than there is space for in the host table.

The example below makes use of the row().child methods to first check if a row is already displayed, and if so hide it (row().child.hide()), otherwise show it (row().child.show()). The content of the child row in this example is defined by the format() function, but you would replace that with whatever content you wanted to show, possibly including, for example, an Ajax call to the server to obtain any extra information.

Upvotes: 1

Views: 2624

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58880

You can use createdRow option to handle event when each row is created and remove class details-control from the first cell based on your condition.

For example:

"createdRow": function( row, data, dataIndex ) {
   if ( data["position"] === "Software Engineer" ) {
      $("td.details-control", row).removeClass("details-control");
   }
}

See this example for code and demonstration.

Upvotes: 2

Related Questions