1

I have a datatable, and I want when I click on a button Hide, go to Database and get the value of status column and hide from the datatable all rows with status column equal to 0.

I tried the following code but doesn't work for me.

var table = $('#example').DataTable();

$("#hide").click(function() {
    $.fn.dataTable.ext.search.push(
      function(settings, data, dataIndex) {
          return $(table.row(dataIndex).node()).attr('status') == 1;
        }
    );
    table.draw();
});    
$("#reset").click(function() {
    $.fn.dataTable.ext.search.pop();
    table.draw();
});

var data = [{
    "id": "1",
    "status": 1,
    "name": "Tiger Nixon",
    "position": "System Architect",
    "salary": "$320,800",
    "start_date": "2011/04/25",
    "office": "Edinburgh",
    "extn": "5421"
  },
  {
    "id": "2",
    "status": 0,
    "name": "Garrett Winters",
    "position": "Accountant",
    "salary": "$170,750",
    "start_date": "2011/07/25",
    "office": "Tokyo",
    "extn": "8422"
  },
  {
    "id": "3",
    "status": 1,
    "name": "Ashton Cox",
    "position": "Junior Technical Author",
    "salary": "$86,000",
    "start_date": "2009/01/12",
    "office": "San Francisco",
    "extn": "1562"
  },
  {
    "id": "4",
    "status": 1,
    "name": "Cedric Kelly",
    "position": "Senior Javascript Developer",
    "salary": "$433,060",
    "start_date": "2012/03/29",
    "office": "Edinburgh",
    "extn": "6224"
  },
  {
    "id": "5",
    "active": 0,
    "name": "Airi Satou",
    "position": "Accountant",
    "salary": "$162,700",
    "start_date": "2008/11/28",
    "office": "Tokyo",
    "extn": "5407"
  },
];

$(document).ready(function() {
  var table = $('#example').DataTable({
    data: data,
    rowId: 'id',
    columns: [{
        targets: 0,
        data: "status",
        render: function(data, type, row) {
          if (type === 'display') {
            return '<input type="checkbox"  class="editor-active">';
          }
          return data;
        },
        className: "dt-body-center"
      },
      {
        "data": "name"
      },
      {
        "data": "position"
      },
      {
        "data": "office"
      },
      {
        "data": "extn"
      },
      {
        "data": "start_date"
      },
      {
        "data": "salary"
      }
    ],

    pageLength: 2,

    order: [
      [1, 'asc']
    ],

    rowCallback: function(row, data) {
      $('input.editor-active', row).prop('checked', data.status== 1).bootstrapToggle({
        size: 'mini'
      });
    }

  });

  $('#example').on('change', 'input.editor-active', function() {
    console.log(table.row($(this).closest('tr')).id());

  });

});

$(document).ready(function() {

  $("#hide").click(function() {
    
  });

});
body {
  font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
  margin: 0;
  padding: 0;
  color: #333;
  background-color: #fff;
}
<!DOCTYPE html>
<html>

<head>
  <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>

  <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
  <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

  <meta charset=utf-8 />
  <title>DataTables - JS Bin</title>
</head>

<body>
  <div class="container">

    <button id="hide">hide data-status=0</button>
    <button id="reset">reset</button>
    <table id="example" class="table table-striped table-bordered" width="100%">
      <thead>
        <tr>
          <th>Checkbox</th>
          <th>Name</th>
          <th>Position</th>
          <th>Office</th>
          <th>Age</th>
          <th>Start date</th>
          <th>Salary</th>
        </tr>
      </thead>

      <tfoot>
        <tr>
          <th>Checkbox</th>
          <th>Name</th>
          <th>Position</th>
          <th>Office</th>
          <th>Age</th>
          <th>Start date</th>
          <th>Salary</th>
        </tr>
      </tfoot>

    </table>
  </div>
</body>

</html>

When for example I switch the checkbox to OFF , the status column in dtatatable change to 0 , Now I want when I click on button hide data-status=0 hide from datatable all rows with checkbox with vvalue off (status in database equal to 0)

Updated

My table :

 <div class="row">
                <div class="col-12 mb-4 data-table-rows data-tables-hide-filter">
                        <table id="datatableRows" class="data-table responsive nowrap"
                            data-order="[[ 1, &quot;desc&quot; ]]">
                            <thead>
                                <tr>
                                    <th>Image</th>
                                    <th>Nom</th>
                                    <th>CIN</th>
                                    <th>Phone</th>
                                   
                                   <th>Action</th> 
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>

Function witch get Data from Database :

function getdata(Request $request)
{
    if(request()->ajax())
    {
        return datatables()->of(Casting::latest()->get())
            ->addColumn('action', function($data){
                $button = '<table><tr><td>';
                $button .= '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Modifier</button>';
                $button .= '</td><td>';
                $button .= ' <label  class="switch" >';
                $button .= '  <input type="checkbox" id="'.$data->id.'" class="switch selectRow" ';
                
                if ($data->status == 1) {

                    $button .= "checked";
                }

                $button .= '><span class="slider round"></span></label>';
                $button .= '</td></tr></table>';

                return $button;
        })
        ->rawColumns(['action'])
        ->make(true);
    }
    return view('Casting.castingss');
}

Function which updates the status value :

  public function changeStatus(Request $request)
    {
       $request->validate(['status'=>'required','id'=>'required']);
        $casting = Casting::find($request->id);
        if($casting){
        $casting->status = $request->status;
        $casting->save();
       return response()->json(['success'=>'Status change successfully.']);
        }
       return response()->json(['failed'=>'Status change failed.'],422);
           
        }

And My script : 

 $('#datatableRows').DataTable({

  processing: true,
  serverSide: true,
  ajax:{
   url: "{{ route('castingss.getdata') }}",
  },
  columns:[
  
   {
    data: 'casting_photo',
    name: 'casting_photo',
    render: function(data, type, full, meta){

              return "<img src={{ URL::to('/') }}/castingimages/" + data +  " class='list-thumbnail responsive border-0 card-img-left' />";
    },
    orderable: false
   },
   {data:'casting_name',
    name: 'casting_name',
    render:function(data,type,full,meta){
      return "<a href='profile'>" + data + "</a>";
    }
   },
    {
    data: 'casting_cin',
    name: 'casting_cin'
   },
   {
   data:   "casting_phone",
   name:   "casting_phone"
   },
   
   {
    data: 'action',
    name: 'action',
    orderable: false
   }
  ] 
 });



$(document).on('change', '.selectRow', function(){

        var status = $(this).prop('checked') == true ? 1 : 0; 

          var id = $(this).attr('id');

            $.ajax({

            type: "get",

            dataType: "json",

            url: '/changeStatus',

            data: {'status': status, 'id': id},

            success: function(data){

              console.log(data.success)

            }

        });


    });

UPDATED2

$('#datatableRows').DataTable({

  processing: true,
  serverSide: true,
  ajax:{
   url: "{{ route('castingss.getdata') }}",
  },
  columns:[
  
   {
    data: 'casting_photo',
    name: 'casting_photo',
    render: function(data, type, full, meta){

              return "<img src={{ URL::to('/') }}/castingimages/" + data +  " class='list-thumbnail responsive border-0 card-img-left' />";
    },
    orderable: false
   },
   {data:'casting_name',
    name: 'casting_name',
    render:function(data,type,full,meta){
      return "<a href='profile'>" + data + "</a>";
    }
   },
    {
    data: 'casting_cin',
    name: 'casting_cin'
   },
   {
   data:   "casting_phone",
   name:   "casting_phone"
   },
   
   {
    data: 'action',
    name: 'action',
    orderable: false
   }
  ] 
 });



$(document).on('change', '.selectRow', function(){

        var status = $(this).prop('checked') == true ? 1 : 0; 

          var id = $(this).attr('id');

            $.ajax({

            type: "get",

            dataType: "json",

            url: '/changeStatus',

            data: {'status': status, 'id': id},

            success: function(data){

              console.log(data.success)

            }

        });


    });



$("#hide").click(function() {

  alert('je suis là');

    $.fn.dataTable.ext.search.push(
      function(settings, data, dataIndex) {
          return $(table.row(dataIndex).node()).find('.selectRow').prop("checked") == true;
        }
    );
    table.draw();
});
$("#reset").click(function() {
  $.fn.dataTable.ext.search.pop();
  table.draw();
});

But nothing occurs

2
  • Not clear why you would be searching for an element attribute and not row data. As for going to the database you would need to use ajax to load more data. Are you rendering html rows server side currently? A minimal reproducible example would be helpful Commented Jun 6, 2021 at 20:30
  • @charlietfl please check my edit Commented Jun 6, 2021 at 21:34

1 Answer 1

1

You can use table.row(dataIndex).data().status to get status value and if its 1 show them else hide . Also, user can check/uncheck your checkboxes so you need to update your status value to 1 or 0 so that next time when you click on reset button it will update rows accordingly else it will hide checked rows as well.

Demo Code :

var data = [{
    "id": "1",
    "status": 1,
    "name": "Tiger Nixon",
    "position": "System Architect",
    "salary": "$320,800",
    "start_date": "2011/04/25",
    "office": "Edinburgh",
    "extn": "5421"
  },
  {
    "id": "2",
    "status": 0,
    "name": "Garrett Winters",
    "position": "Accountant",
    "salary": "$170,750",
    "start_date": "2011/07/25",
    "office": "Tokyo",
    "extn": "8422"
  },
  {
    "id": "3",
    "status": 1,
    "name": "Ashton Cox",
    "position": "Junior Technical Author",
    "salary": "$86,000",
    "start_date": "2009/01/12",
    "office": "San Francisco",
    "extn": "1562"
  },
  {
    "id": "4",
    "status": 1,
    "name": "Cedric Kelly",
    "position": "Senior Javascript Developer",
    "salary": "$433,060",
    "start_date": "2012/03/29",
    "office": "Edinburgh",
    "extn": "6224"
  },
  {
    "id": "5",
    "status": 0,
    "name": "Airi Satou",
    "position": "Accountant",
    "salary": "$162,700",
    "start_date": "2008/11/28",
    "office": "Tokyo",
    "extn": "5407"
  },
];


var table = $('#example').DataTable({
  data: data,
  rowId: 'id',
  columns: [{
      targets: 0,
      data: "status",
      render: function(data, type, row) {
        if (type === 'display') {
          return '<input type="checkbox"  data-toggle="toggle" class="editor-active">';
        }
        return data;
      },
      className: "dt-body-center"
    },
    {
      "data": "name"
    },
    {
      "data": "position"
    },
    {
      "data": "office"
    },
    {
      "data": "extn"
    },
    {
      "data": "start_date"
    },
    {
      "data": "salary"
    }
  ],

  pageLength: 2,

  order: [
    [1, 'asc']
  ],

  rowCallback: function(row, data) {

    $('input.editor-active', row).prop('checked', data.status == 1).bootstrapToggle({
      size: 'mini'
    });
  }

});

$('#example').on('change', 'input.editor-active', function() {
  var datas = table.row($(this).closest('tr')).data(); //get data
  datas.status = $(this).is(":checked") ? 1 : 0; //update status..
  table.row($(this).closest('tr')).data(datas).draw(); //draw row again..
});



$("#hide").click(function() {
  $.fn.dataTable.ext.search.push(
    function(settings, data, dataIndex) {
      //get status value..
      return table.row(dataIndex).data().status == 1
    }
  );
  table.draw();
});
$("#reset").click(function() {
  $.fn.dataTable.ext.search.pop();
  table.draw();
});
<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>

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

<div class="container">

  <button id="hide">hide data-status=0</button>
  <button id="reset">reset</button>
  <table id="example" class="table table-striped table-bordered" width="100%">
    <thead>
      <tr>
        <th>Checkbox</th>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
      </tr>
    </thead>

    <tfoot>
      <tr>
        <th>Checkbox</th>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
      </tr>
    </tfoot>

  </table>
</div>

Update 1 :

You can simply check if the selectRow is checked or not depending on this show rows else hide them .So , jquery code will look like below :

$("#hide").click(function() {
    $.fn.dataTable.ext.search.push(
      function(settings, data, dataIndex) {
          return $(table.row(dataIndex).node()).find('.selectRow').prop("checked") == true;
        }
    );
    table.draw();
});
$("#reset").click(function() {
  $.fn.dataTable.ext.search.pop();
  table.draw();
});
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you for your reply , but in my case I have not the column status in my Table I have just a toggle switch custom whitch updates the status value in database
please check my Updaye , how can I hide the rows with status equal to 0
see my script , I tried ur updated code but doesn't work
Can you show output of console.log($(table.row(dataIndex).node()).html()) of only one node put that line inside function(settings, data, dataIndex) {.. just need to see where selectRow is located .
like that : $("#hide").click(function() { alert('je suis là'); $.fn.dataTable.ext.search.push( function(settings, data, dataIndex) { console.log($(datatableRows.row(dataIndex).node()).html()); } ); table.draw(); });
|

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.