0

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?

Community
  • 1
  • 1
mpsbhat
  • 2,733
  • 12
  • 49
  • 105
  • write your $('#ToggleColumns').click(function () {}); at last after foo() function complete. – herr Sep 15 '14 at 06:16
  • Even though it works once then second time click event is not working. http://jsfiddle.net/eqsadgez/3/ – mpsbhat Sep 15 '14 at 06:20
  • Yes. It may problem in your code inside your click event. Sorry But Actually I don't know about that code. But your click event will occurs. – herr Sep 15 '14 at 06:25

1 Answers1

1

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);
            });
Azadrum
  • 756
  • 6
  • 23