SimplyKz
SimplyKz

Reputation: 45

Show specific child row in datatables on condition

I would like to display child row for specific row on certain condition, let's say for example i only want to show the child row if the child's gender is male, and this info also can be found in the child row itself.

In my code below it expand/collapse all child row. How can i resolve this?

function(data) {
    var table = $('#childInfoTable').DataTable( {   
    ajax: 'childdata',
    "dom": 'rt',
    select:"single",
    "columns": [
                {
                "className": 'childInfoShow',
                "orderable":  false,
                "defaultContent": '',
                width:"15px"
                },
             { "data": "id" },
             { "data": "name" }
             ]
            });

    $('#childInfoTable tbody').on('click', 'td.childInfoShow', function() {

    var tr = $(this).closest('tr');
    var row = table.row(tr);        

    if (row.child.isShown()) {
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        row.child(format(row.data())).show();
        tr.addClass('shown');
        }

});

Upvotes: 0

Views: 1143

Answers (2)

SimplyKz
SimplyKz

Reputation: 45

Ok, I've found a workaround to this by adding on to the if else:

else if (row.data().gender == 'male') {

}
else {
    row.child(format(row.data())).show();
    tr.addClass('shown');
    }

Upvotes: 1

Sree Nath
Sree Nath

Reputation: 543

Check this example. Hope this will help. fnRowCallback() will help you access each row while creating the table, so you could check if the row contains male or female and hide the row according to that. As per this example, if the row contains data which has gender "male", it will hide that particular row.

var data = [{name: "Sri",
gender: 'male'},
{name: "Sara", gender: "female"},
{name:"paul", gender: "male"}
]

$('#dtable').dataTable({
	data: data,
  columns: [{
  	data: 'name'
  },
  {data: 'gender'}],
  fnRowCallback: function(nRow, aData, iDisplayIndex){
  if(aData.gender == 'male'){
  	$(nRow).hide();
  }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<table id="dtable">
  <thead><tr><th>Name</th><th>Gender</th></tr></thead>
  <tbody>
  </tbody>
</table>

Upvotes: 1

Related Questions