Lara Lara - 3 months ago 44
Javascript Question

How to get First column of Jquery Datatable as Checkbox

I have a requirement where I need to add the first column and its subsequent row values as Checked or Unchecked checkbox. The issue that I am facing as of now is one of dynamic data from the server side. Here, both column Name and Row Values are coming from the server side. Here is the code.

$('#SettingsDatatable').dataTable({
"order": [],
"dom": "Bfrtip",
"buttons": ["copy", "csv", "excel", "pdf", "print"],
"columnDefs": [{
"className": "dt-center", "orderable": false, "width": 20
}],
"columns": dataObject[0].columns,
"data": dataObject[0].data
});


How can I add the checkbox column and how can it be checked and unchecked based on the value from
dataObject[0].data
? Please help. Thanks.

JAG JAG
Answer

you can use columnDefs to render custom html

var dataObject = [{
  "columns": [{
    "title": "Select"
  }, {
    "title": "DbColumn Name"
  }, {
    "title": "UserColumn Name"
  }],
  "data": [
    ["False", "STARTDATE", ""],
    ["True", "ENDDATE", ""],
    ["False", "CLASS ", ""],
    ["True", "AUDIT_DATE ", ""]
  ]
}];

$('#SettingsDatatable').dataTable({
  "order": [],
  "dom": "Bfrtip",
  "buttons": ["copy", "csv", "excel", "pdf", "print"],
  "columnDefs": [{
    "targets": 0,
    "render": function(data, type, full, meta) {
      return '<input type="checkbox" ' + (data == 'True' ? 'checked' : '') + ' />';
    }
  }, {
    "className": "dt-center",
    "orderable": false,
    "width": 20
  }],
  "columns": dataObject[0].columns,
  "data": dataObject[0].data
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.1/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.1/css/jquery.dataTables.css" rel="stylesheet" />
<table id="SettingsDatatable"></table>

Comments