mpsbhat
mpsbhat

Reputation: 2773

Button click function not working on datatable toolbar custom button

As continuation to this question,

Myself added the toggle button to datatable toolbar dom element as

 "dom": "T<'clear'><'row DatatableRow'<'col-xs-3'l><'col-xs-3'><'col-xs-3'<'#ToggleButton'>><'col-xs-3 text-right'f>r>t<'row DatatableRow'<'col-xs-3'i><'col-xs-3'><'col-xs-3'><'col-xs-3 text-right'p>>"

and button is added as

$("div#ToggleButton").html('<br/><button type="button" class="btn btn-primary btn-sm" id="ToggleColumns">Toggle</button>');

But in this case, the click function is not working?

Upvotes: 0

Views: 2180

Answers (1)

Azadrum
Azadrum

Reputation: 746

It was not working because you were trying to bind a button that is not yet existed on DOM. And you are recreating the table to change the fixed column index. I cant say this is a good way but i couldnt find to change fixed column of rendered datatable on documentations.

but i fixed your fiddle on your way.

the idea is to bind the button on init of datatable right after adding the custom button html like.

$(document).ready(function () {
    foo(2);

    function foo(columnNumber) {
        table = $('#example').on('init.dt', function () {
            $("div#ToggleButton").html('<br/><button type="button" class="btn btn-primary btn-sm" id="ToggleColumns">Toggle</button>');
            $('#ToggleColumns').click(function () {
                table.destroy();
                debugger;
                if (columnNumber == 2) {
                    columnNumber = 0;
                } else {
                    columnNumber = 2;
                }
                foo(columnNumber);
            });
        }).DataTable({
            scrollY: "300px",
            scrollX: true,
            scrollCollapse: true,
            paging: false,
                "dom": "T<'clear'><'row DatatableRow'<'col-xs-3'l><'col-xs-3'><'col-xs-3'<'#ToggleButton'>><'col-xs-3 text-right'f>r>t<'row DatatableRow'<'col-xs-3'i><'col-xs-3'><'col-xs-3'><'col-xs-3 text-right'p>>",
        });


        new $.fn.dataTable.FixedColumns(table, {
            leftColumns: columnNumber
            //   rightColumns: 1
        });
    }
});

If you can find a way to change the fixedColumn number...

$('#ToggleColumns').click(function () {

// replace the following codes with changing fixedColumn columns
                table.destroy();
                if (columnNumber == 2) {
                    columnNumber = 0;
                } else {
                    columnNumber = 2;
                }
                foo(columnNumber);
            });

Upvotes: 1

Related Questions