简体   繁体   中英

JQuery DataTable plugin column visibility

I have this JQuery DataTable defined:

    APMTable = $(table).DataTable({
        "ajax": {
            "url": AP.APP_ROOT + '/api/'+ AP.WebId + '/' + AP.BillToCompanyKey + '/' + from + '/' + to + '/' + AP.LocaleId + '/' + material,
            "type": "GET"
        },
        columns: [
            { data: "rgNumber" },
            { data: "rgDescription" },
            { data: "rtDescription" },
            { data: "rtNumber" }
        ],
        "responsive": true,
        "order": []
        //"bSort": false
    });

    APMTable.on('xhr.dt',
        function() {
            if (countrycode === 'BR') {
                console.log('SHOW END', countrycode);
                APMTable.column(1).visible(false);
                APMTable.column(2).visible(true);
                APMTable.column(3).visible(true);
            } else {
                console.log('HIDE END', countrycode);
                APMTable.column(1).visible(true);
                APMTable.column(2).visible(false);
                APMTable.column(3).visible(false);
            }
        });

I would like column at index 1 to hide and columns 2 and 3 to show if the countrycode is 'BR'. Vice versa if countrycode is not 'BR', of course.

What happens in reality is that the first time the datatable is rendered and the Ajax call completes, the value 'HIDE END GB' is written to the console, but none of the columns get hidden.

If I then call this:

APMTable.ajax.url( '/api/' + AP.WebId + '/' + from + '/' + to + '/' + LocaleId + '/' + material).load();

The Ajax event listener fires again and the columns hide.

I'm confused because the console.log() statement is written at the same time the first column hide is attempted, but no columns become hidden. Is the datatable firing a separate event I don't know about after rendering the columns?

Do I need to use a timeout to make the columns hide the first time or is there something else going on?

If value of countrycode is known before initializing the table I would rewrite is as follows:

APMTable = $(table).DataTable({
    "ajax": {
        "url": AP.APP_ROOT + '/api/'+ AP.WebId + '/' + AP.BillToCompanyKey + '/' + from + '/' + to + '/' + AP.LocaleId + '/' + material,
        "type": "GET"
    },
    columns: [
        { data: "rgNumber" },
        { data: "rgDescription", visible: (countrycode == 'BR' ? false : true ) },
        { data: "rtDescription", visible: (countrycode == 'BR' ? true : false ) },
        { data: "rtNumber", visible: (countrycode == 'BR' ? true : false ) }
    ],
    "responsive": true,
    "order": []
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM