1

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}
      ]

    });
  });

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried this, and the table doesn't show anymore :(
@user5156944, try to include only drawCallback part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.