How to set 'targets' Dynamically in columnDefs

How to set 'targets' Dynamically in columnDefs

armashansariarmashansari Posts: 2Questions: 2Answers: 0
edited January 2020 in Free community support

I'm having datatable and dropdown. Dropdown having a list of columns. I want to exclude the selected column from search. I want to set 'targets' dynamically in columnDefs when User changes dropdown

This is my code:

    var columns = [];
    //When I hardcode like this: var columns = [0, 1, 2] it works fine
    $(document).ready(function () {
        getData();
        columns.push(eval($('#dropdown').val()));
        $('#dropdown').change(function () {
            columns = [];
            columns.push(eval($('#dropdown').val()));
        })
    });

    function getData() {
        $('#MyTable').DataTable({
            dom: 'Bfrtip',
            ajax: ({
                type: "POST",
                url: "API/Users.asmx/getData",
                dataType: "json",
                dataSrc: function (data) {
                    buildMyDatatable(data)
                }
            }),
            columnDefs: [
                { "searchable": false, "targets": columns } //I want this to be dynamic
            ]
        });
    }

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    By the time you're adding to columns[] you've already initialised the table.

    Kevin's final comment on this thread should help, since it's discussing this kind of thing.

    Colin

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    You can use a class name with columnDefs.targets . The docs has an example.

    Kevin

This discussion has been closed.