DataTables - checkbox with 'onchange' not working

Viewed 1210

I am using dataTables and want to include a checkbox that will update my data when changed (select, deselect). The data is displayed in the table with the checkbox on each row; however:

  1. this.checked is not recognised (returns 'undefined'); and
  2. When I select or deselect a checkbox I get an error in the console log: Uncaught SyntaxError: Unexpected token ','

The code is:

{data: null,
  className: "center",
  render: function(data,type,row) {
      return ("<input type='checkbox' id=" + data.cdId + " name='update' onchange='ymActivityPatrolFunction(" + data.cdId + ", " + this.checked + ")' style='zoom: 2.0;'>")
     },
},

Which gives:

1 Answers

You can pass only this inside your function then to get other value you can use attr("id") to get cdId value and checked to get checked values i.e : true/false.

Demo Code :

var data = [{
    "cdId": "1gh",
    "name": "Tiger Nixon",
  },
  {
    "cdId": "2htf",
    "name": "Garrett Winters"
  },

];


var table = $('#example').DataTable({
  data: data,
  columns: [{
      targets: 0,
      data: "cdId",
      render: function(data, type, row) {
        //use only `this` and change data to `data.cdId` this is for dmo only..
        return ("<input type='checkbox' id=" + data + " name='update' onchange='ymActivityPatrolFunction(this)' style='zoom: 2.0;'>")
      },
      className: "center"
    },
    {
      "data": "name"
    }
  ]
});

function ymActivityPatrolFunction(checkeds) {
  //get id..and check if checked
  console.log($(checkeds).attr("id"), checkeds.checked)

}
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.16/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/dt-1.10.16/datatables.min.js"></script>
<table id="example" class="table table-striped table-bordered" width="100%">
  <thead>
    <tr>
      <th>Checkbox</th>
      <th>Name</th>

    </tr>
  </thead>

  <tfoot>
    <tr>
      <th>Checkbox</th>
      <th>Name</th>

    </tr>
  </tfoot>

</table>

Related