How to integrate the column search engine, above it and not below, Jquery Datatables

0

very good, I'm using the jquery plugin link

which add a select option search engine by columns, which are integrated below the datatable, what I want is that it is shown above next to the search that comes in the plugin, I do not know how to position it in this way.

here the datatable code:

$ (document) .ready (function () {    var table = $ ('# example'). DataTable ({

  columnDefs: [
     {
        targets: 0,
        checkboxes: {
           selectRow: true
        }
     }
  ],
  select: {
     style: 'multi'
  },
  order: [[1, 'asc']]

});

table.column(4).every( function () {

var column = this;
var select = $('<select><option value="">Seleccione...</option></select>')
  .appendTo($(column.footer()).empty())
  .on('change', function() {
    var val = $.fn.dataTable.util.escapeRegex(
      $(this).val()
    );

    column
      .search(val ? '^' + val + '$' : '', true, false)
      .draw();
  });

column.data().unique().sort().each(function(d, j) {
  select.append('<option value="' + d + '">' + d + '</option>')
});

The first part is from the checkboxes, the second from the table. column is the search engine. I would really appreciate the help, greetings!

    
asked by Demaro Create 02.03.2017 в 15:21
source

2 answers

1

I prefer to work with custom filters as the datatables plugin offers, it's very simple. Here is a practical example:

Filtering Html:

<div class="form-group">
    <label for="filter_campo" class="control-label col-md-2">Nombre: </label>
    <div class="col-md-10"> 
        <input type="text" class="form-control" id="filter_campo" name="filter_campo">
    </div>
</div>
<br/><br/>
<div class="form-group">
    <label for="estados" class="control-label col-md-2">Estado: </label>
    <div class="col-md-10"> 
        <select id='estados' name='estados' class='form-control'>
            <option value="" disabled="disabled" selected="true">Elija...</option>
            <option value="true">Activos</option>
            <option value="false">Inactivos</option>
            <option value="">Todos</option>
        </select>
    </div>
</div>

Html of the table:

<table class="display" id="table" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Nº</th>
            <th>Procesos Productivos</th>
            <th>Nombre</th>
            <th>Estado</th>
            <th>Acción</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Nº</th>
            <th>Procesos Productivos</th>
            <th>Nombre</th>
            <th>Estado</th>
            <th>Acción</th>
        </tr>
    </tfoot>
</table>

Ajax where I form my datatables in the view:

var table = $('#table').DataTable({
    "filter": false,
    "destroy": true,
    "responsive": true,
    "processing": true,
    "serverSide": true,
    "ajax": {
        url: 'tabla/procesos',
        global: false,
        method: 'POST',
        data: function (d) {
            d.campo = $('input[name=filter_campo]').val();//aca obtengo el valor del campo "filter_campo"
            d.status = $('select[name=estados]').val();//aca obtengo el valor del select "estados"

        }
    },
    "columns": [
        {data: 0, searchable: false, orderable: false, render: function( data, type, full, meta ){
                return meta.row+1;
            }
        },
        {data: 1},
        {data: 2},
        {"render": function ( data, type, row ) {
            return ButtonEstado(row[3]);
        }},
        {"render": function () {
            return ButtonEditar() + ' ' + ButtonEliminar();
        }},
    ],
    "fnDrawCallback": function() {
        StyleCheckbox();
    },
    order: [[1, 'asc']],    
    "language": {
        "url": "js/idioma_espaniol_datatables.js"
    },
    initComplete: function (data) {

        $('#filter_campo').keyup(function(e) { //cada vez que suelta una tecla
            table.draw(); //refresca la tabla
            e.preventDefault();
        });

        $('#estados').on( 'change', function (e) {//cada vez que cambia de valor el select
            table.draw(); //refresca la tabla
            e.preventDefault();
        });
    }
});

Driver:

$sql = Procesos::select(array
                    (
                        'procesos.id', 
                        'ldp.nombre as ldp', 
                        'procesos.nombre', 
                        'procesos.status', 

                        'procesos.id_lineas_de_produccion'
                    )
                )
               ->join('lineas_de_produccion as ldp','procesos.id_lineas_de_produccion','=','ldp.id');
return Datatables::of($sql)
->filter(function ($query) use ($request) {
    if ($request->has('campo')) { //aca verifico que el campo exista
        $query->where('nombre', 'ilike', "%{$request->get('campo')}%"); //y aca realizo la busqueda por ilike a través del valor del campo de la vista
    }
    if ($request->has('status')) {  //aca verifico que el campo exista
        $query->where('status', '=', "{$request->get('status')}"); //aca realizo filtro la consulta por el where cuando sea status
    }
//estos filtrados los puedes usar a tu creatividad, yo tengo algunos muchos mas complejos. Todo depende de ti.
})
->make();

The source where I learned to do it is this link .

Update 1

As it says in the comments the user @AngelFragaParodi does not specify which side is the filtering, it is server side, and the example I give is done with laravel. With a little knowledge you can migrate to another framework quietly, some other searches in google solve it, it's just a matter of digging a little bit more. But the essence of the custom filtering and the plasma: D

    
answered by 02.03.2017 в 16:12
0

I've been looking for it for a while, but as I feared or modified the plugin or do it by hand.

This plugin packages the table in a div with id as the table, that is, if you have a table with id mitabla , you will create a div with id: mitabla_wrapper . The same goes for the div that contain the buttons, and the search field.

Looking over the documentation a bit, you can define the search behavior by passing a function to it, for example MySearch .

All this can allow us to create the select element ourselves and embed it in the div that we want, for example mitabla_filter , which is where is the search field.

We can increase the size, move to our whim etc, using jquery or javascript native, and that's to everyone's taste.

In this way our search function miSearch would take into account the selected value of our select element while it is running and we will also have our select positioned where we want.

EYE! you'll have to take into account the different events that render the table and build the table again, but I guess there's also some option in the API for that.

In short, for what you want, you have to do it by hand. If you have any questions, do not hesitate to propose it again.

UPDATE

I kept thinking about it, you can do it with CSS and javascript, in the following way without adding any elements and much simpler.

$('#idDeMiTabla_filter').css('float','left');
$('#idDeMiTabla_filter').prev('div').css('float','right');
$('#idDeMiTabla_filter').prev('div').width(
   $('#idDeMiTabla_filter').parent('div').width() - 
   $('#idDeMiTabla_filter').width()
)

What we are doing is changing the position between the two elements above and then giving the first one the width that remains to subtract the width of the #idDeMiTabla_filter from the father of both. This option is less invasive than the previous one.

    
answered by 02.03.2017 в 16:06