Home > Net >  Laravel how to create filter by date for table
Laravel how to create filter by date for table

Time:07-15

so I made an update to my table so the user can search the data filtered by date (year), by adding a drop down menu for the selection. I'm trying to use ajax to filter the date, but somehow I can't get it to work. May I know what is wrong with my code? Or is there another way to filter my table by date?

Blade file for the table view

<section >
    <div >
        <div >
            <div >
              <div >
                <div >
                  <h3 >Tabel Pekerjaan</h3>
                  <br>
                  <div >
                    <a href="/tambahpekerjaan" type="button" ><i ></i>&nbsp Tambah Pekerjaan</a>
                  </div>

                  <div >
                      <select id="filter-tahun" >
                        <option value="">Pilih Tahun</option>
                        @foreach ($pekerjaan as $pekerjaans)
                          <option value="{{$pekerjaans->id}}">{{$pekerjaans->tanggal}}</option>
                        @endforeach
                      </select>
                  </div>
                </div>
                <!-- /.card-header -->
                <div >
                  <table id="tabelpekerjaan" >
                    <thead>
                      <tr>
                        <th style="width: 10px">No.</th>
                        <th>Paket Pekerjaan</th>
                        <th>Tanggal</th>
                        <th>Nama Perusahaan</th>
                        <th>Lokasi Pekerjaan</th>
                        <th>PPK</th>
                        <th>HPS</th>
                        <th>Gambar</th>
                        <th style="width: 120px">Aksi</th>
                      </tr>
                    </thead>
                    <tbody>
                      @php $no = 1; @endphp
                      @foreach ($pekerjaan as $pekerjaans)
                      <tr>
                        <td>{{$no  }}</td>
                        <td>{{$pekerjaans->pekerjaan}}</td>
                        <td>{{$pekerjaans->tanggal}}</td>
                        <td>{{$pekerjaans->penyedia->nama}}</td>
                        <td>{{$pekerjaans->lokasi}}</td>
                        <td>{{$pekerjaans->user->name}}</td>
                        <td>Rp. {{number_format($pekerjaans->hps,0,',',',')}}</td>
                        <td>
                          <img src="{{asset('gambarpekerjaan/'.$pekerjaans->gambar)}}" style="width: 100px"alt="">
                        </td>
                        <td>
                            @if (Auth::user()->status=='super')
                              <a href="/editpekerjaan/{{$pekerjaans->id}}" type="button" >Edit</a>
                              <a href="#" type="button"  data-id="{{$pekerjaans->id}}" data-nama="{{$pekerjaans->pekerjaan}}">Hapus</a>
                            @else
                            <a href="/editpekerjaan/{{$pekerjaans->id}}" type="button" >Edit</a>
                              
                            @endif
                        </td>
                      </tr>
                      @endforeach
                    </tbody>
                  </table>
                </div>
                <!-- /.card-body -->
              </div>
              <!-- /.card -->
  
            
    </div>
</section>

here is the script

<script>
  
  $(function () {
    // let pekerjaan = $("#filter-tahun").val();
    
    /*const table =*/ $('#tabelpekerjaan').DataTable({
      "paging": true,
      "lengthChange": true,
      "searching": true,
      "ordering": true,
      "info": true,
      "autoWidth": true,
      "responsive": true,
      // "ajax":{
      //   url: "{{url('')}}/datapekerjaan",
      //   type:"POST",
      //   data:function(d){
      //     d.pekerjaan = pekerjaan;
      //     return d
      //   }
      // }
    });

    //Initialize Select2 Elements
    $('.select2bs4').select2({
      theme: 'bootstrap4'
    })
  });

  
  @if (session()->has('message'))
    toastr.success("{{session()->get('message')}}")  
  @endif

  $('.delete').click(function(){
    var idpekerjaan = $(this).attr('data-id');
    var namapekerjaan = $(this).attr('data-nama');

    Swal.fire({
  title: 'Apakah Anda yakin?',
  text: "Paket Pekerjaan " namapekerjaan " akan dihapus!",
  icon: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Ya, yakin!'
}).then((result) => {
  if (result.isConfirmed) {
    window.location = "/deletepekerjaan/" idpekerjaan ""
    Swal.fire(
      'Dihapus!',
      'Data berhasil dihapus.',
      'success'
    )
  }
});
  });

  // $(".filter").on('change',function(){
  //   pekerjaan = $("#filter-tahun").val()
  //   table.ajax.reload(null,false)
  // })
</script>

I commented on the ajax's part since it doesn't work at all and my table become a mess...

May I know how to resolve this problem? Thank in advance

CodePudding user response:

Check This

$(document).ready(function () { // Setup - add a text input to each footer cell $('#example thead tr') .clone(true) .addClass('filters') .appendTo('#example thead');

var table = $('#example').DataTable({
    orderCellsTop: true,
    fixedHeader: true,
    initComplete: function () {
        var api = this.api();

        // For each column
        api
            .columns()
            .eq(0)
            .each(function (colIdx) {
                // Set the header cell to contain the input element
                var cell = $('.filters th').eq(
                    $(api.column(colIdx).header()).index()
                );
                var title = $(cell).text();
                $(cell).html('<input type="text" placeholder="'   title   '" />');

                // On every keypress in this input
                $(
                    'input',
                    $('.filters th').eq($(api.column(colIdx).header()).index())
                )
                    .off('keyup change')
                    .on('change', function (e) {
                        // Get the search value
                        $(this).attr('title', $(this).val());
                        var regexr = '({search})'; //$(this).parents('th').find('select').val();

                        var cursorPosition = this.selectionStart;
                        // Search the column for that value
                        api
                            .column(colIdx)
                            .search(
                                this.value != ''
                                    ? regexr.replace('{search}', '((('   this.value   ')))')
                                    : '',
                                this.value != '',
                                this.value == ''
                            )
                            .draw();
                    })
                    .on('keyup', function (e) {
                        e.stopPropagation();

                        $(this).trigger('change');
                        $(this)
                            .focus()[0]
                            .setSelectionRange(cursorPosition, cursorPosition);
                    });
            });
    },
}); });

Refer This https://datatables.net/extensions/fixedheader/examples/options/columnFiltering.html

  • Related