首页 > 解决方案 > 使用 laravel 和 Ajax 根据列的值隐藏数据表中的行

问题描述

我有一个数据表,当我单击一个按钮隐藏时,我想要,转到数据库并获取状态列的值并从数据表中隐藏状态列等于 0 的所有行。

我尝试了以下代码,但对我不起作用。

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>

例如,当我将复选框切换为 OFF 时, dtatatable 中的状态列更改为 0 ,现在我想当我单击按钮时hide data-status=0从数据表中隐藏所有行,复选框中的 vvalue 关闭(数据库中的状态等于 0)

更新

我的桌子:

 <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 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');
}

更新状态值的函数:

  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)

            }

        });


    });

更新2

$('#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();
});

但什么也没有发生

标签: jqueryajaxlaravel

解决方案


您可以table.row(dataIndex).data().status用来获取状态值,如果它1显示它们,则隐藏。此外,用户可以选中/取消选中您的复选框,因此您需要更新您的状态值,1以便0下次单击reset按钮时它会相应地更新行,否则它也会隐藏选中的行。

演示代码

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>

更新 1

您可以selectRow根据此显示行简单地检查是否已检查,否则将其隐藏。因此,jquery 代码将如下所示:

$("#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();
});

推荐阅读