jane doe
jane doe

Reputation: 69

Toggle Switch on Datatables using Laravel

I am trying to add a column for a toggle switch in my data table, but it's not working. It's just showing this text

Image 1

When it should be like this

Image 2

These are my codes

$(function(){
    $('#table').DataTable({
      processing: true,
      serverSide: true,
      ajax: '{!! URL::asset('/amenity/table') !!}',
      columns : [
        { data: function (data) {return '<a href="amenity-details?id=' + data.id + '">' + data.name + '</a>';}, name: 'name' },
        { data: 'dayrate', name: 'dayrate' },
        { data: 'nightrate', name: 'nightrate' },
        { data: function(data){
            return '<div class="switch switch-square" data-on-label=\"<i class=" fa fa-check"></i>\" data-off-label=\"<i class="fa fa-times"></i>\"> <input type="checkbox" class="status '+data.status+'" data-id="'+data.id+'" /></div>';
        }, name: 'state', orderable: true, searchable: false},
        { data: 'action', name: 'action', orderable: false, searchable: false}
      ]

    });
  });

Upvotes: 1

Views: 2387

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58880

CAUSE

Since your switch is added at later time after ready event, it doesn't get initialized.

SOLUTION

You need to initialize controls used in jQuery DataTable each time the table is redrawn. Use drawCallback option to define a function that will be called every time the table has been redrawn.

For example:

$('#table').DataTable({
   // ... skipped ...
   drawCallback: function(settings){
      var api = new $.fn.dataTable.Api( settings );

      // Initialize switch
      $('.switch', api.table().body()).bootstrapSwitch(); 
   }
});

LINKS

See jQuery DataTables: Custom control does not work on second page and after for more examples and details.

Upvotes: 1

Related Questions