Search code examples
javascriptjquerydatatables

How to put a condition at Datatables button?


How to put a condition to check if data not null then "Not Found" button will appear, otherwise it will be hidden. Assuming client side received Ajax response from API.

enter image description here

success: function(response){
    var result;
    
    if (response.data != null){
        result = "dataNotNull";
    } else {
        result = "dataNull";
    }

    loadFunc(result);
}

function loadFunc(result){
    $('#myTable').DataTable({
        buttons: [
            {
                text: 'Missmatch',
                titleAttr: 'Download in Excel',
                action: function ( e, dt, node, config ) {
                    func_expMissMatch();
                }
            },
            {
                text: 'Not Found',
                titleAttr: 'Download in Excel',
                action: function ( e, dt, node, config ) {
                    func_expNotFound();
                }
            }
        ]
    });
}

Solution

  • try this:

    function loadFunc(result){
        let buttons = [];
        if (result === "dataNotNull") {
            buttons.push({
                text: 'Missmatch',
                titleAttr: 'Download in Excel',
                action: function ( e, dt, node, config ) {
                    func_expMissMatch();
                },
            });
        }
        else{
            buttons.push({
                text: 'Not Found',
                titleAttr: 'Download in Excel',
                action: function ( e, dt, node, config ) {
                    func_expNotFound();
                },
            });
        }
        $('#myTable').DataTable({
            buttons: buttons,
        });
    }