Remove/Delete Datatable Row If Condition Not Met

Remove/Delete Datatable Row If Condition Not Met

murday1983murday1983 Posts: 29Questions: 12Answers: 0

I cant seem to get this right hence my question.

I have a datatable on my page which is called on a button click. The table displays my JSON fine but i have a requirement which deepening on which way the user entered the page determines which results should be displayed and this is the bit i'm struggling with.

This is what i get back in my data for each row

Which displays as

What i'm after is if the code returned does not equal 316 (for example) then do not add the row, this is where i'm falling down.

Below is all my code i have to generate my datatable.The commented out code, is what i have tried but where i have failed.

callRatesDataTable = $('#callRatesDataTable').DataTable({
    "ordering": true, // Allows ordering
    "paging": true, // Pagination
    "searching": true, // Searchbox
    "info": false, // Shows 'Showing X of X' information
    "pagingType": 'simple_numbers', // Shows Previous, page numbers & next buttons only
    "pageLength": 10, // Defaults number of rows to display in table. If changing this value change the show/hide below
    "dom":
    "<'form-group row buttonRow'<'col-12 text-right'B>>" +
    "<'row dropdownPageRow'<'col-6'l><'col-6'p>>" +
    "<'row'<'col-12'tr>>" +
    "<'row'<'col-6'l><'col-6'p>>",
    "lengthMenu": [
    [10, 25, 50, -1],
    [10, 25, 50, "All"]
    ],
    "buttons": [
    {
        extend: 'csv',
        text: '<i class="fas fa-file-csv" style="font-size: large"></i>',
        titleAttr: 'Click to download as a CSV',
        filename: 'List of accounts',
        className: 'd-flex align-items-center btn roundButton d-flex align-items-center justify-content-center lightYellowButton mb-0 roundButton',
    },
    {
        extend: 'pdf',
        orientation: 'landscape',
        text: '<i class="far fa-file-pdf" style="font-size: large"></i>',
        titleAttr: 'Click to download as a PDF',
        filename: 'List of accounts',
        className: 'd-flex align-items-center btn roundButton d-flex align-items-center justify-content-center lightYellowButton mb-0 roundButton',
    },
    {
        extend: 'print',
        text: '<i class="fas fa-print" style="font-size: large"></i>',
        titleAttr: 'Click to print the results',
        className: 'd-flex align-items-center btn roundButton d-flex align-items-center justify-content-center lightYellowButton mb-0 roundButton'
    }
    ],
    "fnDrawCallback": function () { },
    "language": {
        "lengthMenu":
        "<span class='mb-2' style='display: flex'>" +
        "<span class='mr-2 d-flex align-items-center'>Displaying</span>" +
        "_MENU_" +
        "<span class='ml-2 d-flex align-items-center'>records</span>" +
        "</span>"
    },
    "ajax": {


          "type": 'GET',
            "url": 'test_JS_Files/jsonFiles/reseller_CallRates.json',
            // "data": function (data) {
            //     return data;
            // },
            "dataSrc": function (res) {
                // let data = res.data;

                // var filtered = data.filter(function (code, index, arr,) {
                //     return code[0] != 599;
                // });

                // console.log(filtered)
                // return filtered
                return res.data;
            },
            "error": function () {
            $('#callRatesDataTable_wrapper').hide();
            $('#existingRuleLoadErrorMessage').html(
                '<p>There was an issue retrieving data. Please try again.</p>' +
                '<p>If the error keeps occurring, please get in touch.</p>').addClass('text-danger');
        }
    },
    "columns": [
    {
        "data": null,
        "render": function (data) {
            return data.location.charAt(0).toUpperCase() + data.location.slice(1).toLowerCase();
        }
    },
    {
        "sorting": false,
        "data": null,
        "render": function (data) {
            peakcharge = data.peakcharge;
            peakcharge = +peakcharge;

            if ($('#rateIncreaseField').val() != '') {
                percentAmount = (peakcharge / 100) * percentAmountField
                peakcharge = peakcharge + percentAmount;
                peakcharge = peakcharge.toFixed(6);
            }

            return '<div class="input-group"><div class= "input-group-prepend"><span class="input-group-text font-weight-bold">£</span></div>' +
            '<input name="peakchargeField" class="form-control col-6" type="number" min="0" placeholder="Enter an amount" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" value="' + peakcharge + '" disabled>' +
            '</div>';
        }
    },
    {
        "sorting": false,
        "data": null,
        "render": function (data) {
            offpeakcharge = data.offpeakcharge
            offpeakcharge = +offpeakcharge;

            if ($('#rateIncreaseField').val() != '') {
                percentAmount = (offpeakcharge / 100) * percentAmountField
                offpeakcharge = offpeakcharge + percentAmount;
                offpeakcharge = offpeakcharge.toFixed(6);
            }

            return '<div class="input-group"><div class= "input-group-prepend"><span class="input-group-text font-weight-bold">£</span></div>' +
            '<input name="offpeakchargeField" class="form-control col-6" type="number" min="0" placeholder="Enter an amount" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" value="' + offpeakcharge + '" disabled>' +
            '</div>';
        }
    },
    {
        "sorting": false,
        "data": null,
        "render": function (data) {
            connectioncharge = data.connectioncharge
            connectioncharge = +connectioncharge;

            if ($('#rateIncreaseField').val() != '') {
                percentAmount = (connectioncharge / 100) * percentAmountField
                connectioncharge = connectioncharge + percentAmount;
                connectioncharge = connectioncharge.toFixed(6);
            }

            return '<div class="input-group"><div class= "input-group-prepend"><span class="input-group-text font-weight-bold">£</span></div>' +
            '<input name="connectionchargeField" class="form-control col-6" type="number" min="0" placeholder="Enter an amount" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" value="' + connectioncharge + '" disabled>' +
            '</div>';
        }
    },
    {
        "data": null,
        "render": function (data) {
            return data.manuallyupdated.charAt(0).toUpperCase() + data.manuallyupdated.slice(1).toLowerCase();
        }
    },

    ],
    "createdRow": function () {
        // var table = $('#callRatesDataTable').DataTable();

        // $('#callRatesDataTable').DataTable().rows().eq(0).each(function (index) {
        //     var row = $('#callRatesDataTable').DataTable().row(index);
        //     var data = row.data();
        //     var currentPosition = data.code;

        //     if (currentPosition == 517) {
        //         $('tr').addClass('conMet');
        //     } else {
        //         $('tr').addClass('conNotMet');
        //     }
        // });


        // table.row('.conMet').remove().draw(false);       
    },
    "initComplete": function () {
        window.hideLoader();
        // var table = $('#callRatesDataTable').DataTable();

        // $('#callRatesDataTable').DataTable().rows().eq(0).each(function (index) {
        //     var row = $('#callRatesDataTable').DataTable().row(index);
        //     var data = row.data();
        //     var currentPosition = data.code;

        //     if (addResellerPath && currentPosition == 599) {
        //         $('tr').addClass('conMet');
        //     } else {
        //         $('tr').addClass('conNotMet');
        //     }
        // });

        // table.row('.conMet').remove().draw(false);
    },
    "destroy": true
});

JSON file code

{
    "data": [
        {
            "location": "One",
            "code": 316,
            "peakcharge": "0.002550",
            "offpeakcharge": "0.002500",
            "connectioncharge": "0.000000",
            "manuallyupdated": "yes"
        },
        {
            "location": "Two",
            "code": 3000,
            "peakcharge": "0.003000",
            "offpeakcharge": "0.003000",
            "connectioncharge": "0.000000",
            "manuallyupdated": "no"
        },
        {
            "location": "Three",
            "code": 3001,
            "peakcharge": "0.005000",
            "offpeakcharge": "0.005000",
            "connectioncharge": "0.000000",
            "manuallyupdated": "no"
        }
    ]
}

Looking at the JSON file code i don't want to display codes '3000' & '3001'

If i look at my console.log for in the dataSrc i get this

I would have thought that as per the commented out code, it should have ignored this row (P.S i know the code number is different in this example to the ones mentioned but this was just an example to see if i could exclude it)

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,192Questions: 1Answers: 10,412 Site admin
    Answer ✓

    Your ajax.dataSrc is the right sort of way to go, but not quite right. For example, rather then using [0] as an array index, your data is objects, so use .code.

                "dataSrc": function (res) {
                    let data = res.data;
     
                    var filtered = data.filter(function (code, index, arr,) {
                        return code.code !== 3000 && code.code !== 3001;
                    });
     
                    return filtered
                },
    

    Allan

  • murday1983murday1983 Posts: 29Questions: 12Answers: 0

    @allan I was about to post the same solution as you. I tried this before reading your answer but thank you.

This discussion has been closed.