Datatable column filter Asp net mvc5

Asked

Viewed 516 times

2

I have a problem using the plugin datatables column filter, it does not report me error but also does not generate filters, follow my code:

<script language="JavaScript">
        $(document).ready(function () {
            $('#myTable tfoot th').each(function () {
                var title = $('#myTable thead th').eq($(this).index()).text();
                $(this).html('<input type="text" placeholder="Search ' + title + '" />');
            });

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

            table.columns().every(function () {
                var that = this;

                $('input', this.footer()).on('keyup change', function () {
                    that
                        .search(this.value)
                        .draw();
                });
            });
        });
    </script>
    <script>
        $(document).ready(function () {
            $('#myTable').DataTable({
                "dom": 'C<"clear">lfrtip',
                "language": {
                    "sEmptyTable": "Nenhum registro encontrado",
                    "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
                    "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
                    "sInfoFiltered": "(Filtrados de _MAX_ registros)",
                    "sInfoPostFix": "",
                    "sInfoThousands": ".",
                    "sLengthMenu": "_MENU_ resultados por página",
                    "sLoadingRecords": "Carregando...",
                    "sProcessing": "Processando...",
                    "sZeroRecords": "Nenhum registro encontrado",
                    "sSearch": "Pesquisar",
                    "oPaginate": {
                        "sNext": "Próximo",
                        "sPrevious": "Anterior",
                        "sFirst": "Primeiro",
                        "sLast": "Último"
                    },
                    "oAria": {
                        "sSortAscending": ": Ordenar colunas de forma ascendente",
                        "sSortDescending": ": Ordenar colunas de forma descendente"
                    }
                }, scrollY: 2, scrollX: 300, searching: true, retrieve: true, ordering: false, rowReorder: true
            });
        });
    </script>

my table:

 @using (@Html.BeginForm("Salvar", "AcompanhamentoEntrega", FormMethod.Post))
            {
                <div id="tabelaFenix">
                    <table id="myTable" class="stripe table compact hover" cellspacing="0">
                        <thead style="position:static">
                            <tr>
                                <th align="left" style="font-size:10px">DATA EXPEDIÇÃO</th>
                                <th align="left" style="font-size:10px">STATUS ENTREGA</th>
                                <th align="left" style="font-size:10px">DATA ENTREGA</th>
                                <th align="left" style="font-size:10px">CONFIRMACAO</th>
                            </tr>
                        </thead>
                        @for (int i = 0; i < Model.listaEntrega.Count(); i++)
                        {
                            <tr>
                                <td height="2px"> @Html.TextBoxFor(m => m.listaEntrega[i].data_expedicao, new { @readonly = "readonly", @size = "4px", @class = "form-controldata_expedicao" })</td>
                                <td height="2px"> @Html.TextBoxFor(m => m.listaEntrega[i].status_entrega, new { @readonly = "readonly", @size = "4px", @class = "form-controldata_expedicao" })</td>
                                <td height="2px"> @Html.TextBoxFor(m => m.listaEntrega[i].data_entrega, new { @readonly = "readonly", @size = "10px", @class = "form-controldata_expedicao" }) </td>
                                <td height="2px"> @Html.TextBoxFor(m => m.listaEntrega[i].confirmacao, new { @readonly = "readonly", @size = "18px", @class = "form-controldata_expedicao" }) </td>
                            </tr>
                        }
                    </table>
                </div>
            }

My time:

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">

<script type="text/javascript" src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

@Styles.Render("~/Content/bootstrap.css")
@Scripts.Render("~/bundles/modernizr")

Link do datatables: https://datatables.net/examples/api/multi_filter.html
  • Generating the filters, you say, is relative to the columns that do not appear the filtering options, right?

  • that’s right, this filter should generate one filter per column, but it is not generating, nor does it return an error by debug

  • Have you tried inspecting the page to see if there has been an error with Datatables?

  • Yes, the only error is that I tried to start twice, but I took the function that translates and does not return any kind of error.

  • Instead, I would go back a little bit in the tutorials of Datatables and put the simplest filter possible.

  • I am currently using the global filter, but it is not completely accurate, in case I need to filter two date fields, the filter will not be necessary understood? I don’t know if it’s an incompatibility with mvc5

  • I don’t think that’s it. MVC is one thing, and Datatables is another. Do you have a link where you started making this change? Maybe it’s just some adjustment.

Show 3 more comments

2 answers

2

By default, the dataTables has a global filter, where it filters the data of all table elements. By your question you are wanting a filter in each column. For this, just modify in order to add a input in each header, to carry out the search, that would be your code:

    // Setup - Adicioona o input no header da tabela
$('#myTable thead tr#filterrow th').each( function () {
    var title = $('#myTable thead th').eq( $(this).index() ).text();
    $(this).html( '<input type="text" onclick="stopPropagation(event);" placeholder="Busca em '+title+'" />' );
} );

// DataTable
var table = $('#myTable').DataTable();

// Aplica o filtro nas colunas
$("#myTable thead input").on( 'keyup change', function () {
    table
        .column( $(this).parent().index()+':visible' )
        .search( this.value )
        .draw();
} );

  function stopPropagation(evt) {
    if (evt.stopPropagation !== undefined) {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
}

You can see a functional example on Jsfiddle.

Response withdrawn on the basis of forum do dataTables.

  • Filters still do not appear, although the page itself does not return any error in the browser.

0

Kind of late (only 4 years), but I’m responding to reference server for those who had this problem.

The author of the question is trying to execute the function in the footer element of the table and it does not exist.

In addition, the code also requires the correct id in Js.

The code below should work on Razor:

        $(document).ready(function () {
            $('#tabelaFenix').DataTable({
                "dom": 'C<"clear">lfrtip',
                "language": {
                    "sEmptyTable": "Nenhum registro encontrado",
                    "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
                    "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
                    "sInfoFiltered": "(Filtrados de _MAX_ registros)",
                    "sInfoPostFix": "",
                    "sInfoThousands": ".",
                    "sLengthMenu": "_MENU_ resultados por página",
                    "sLoadingRecords": "Carregando...",
                    "sProcessing": "Processando...",
                    "sZeroRecords": "Nenhum registro encontrado",
                    "sSearch": "Pesquisar",
                    "oPaginate": {
                        "sNext": "Próximo",
                        "sPrevious": "Anterior",
                        "sFirst": "Primeiro",
                        "sLast": "Último"
                    },
                    "oAria": {
                        "sSortAscending": ": Ordenar colunas de forma ascendente",
                        "sSortDescending": ": Ordenar colunas de forma descendente"
                    }
                }, scrollY: 2, scrollX: 300, searching: true, retrieve: true, ordering: false, rowReorder: true
            });
            
            $('#tabelaFenix tfoot th').each(function () {
                var title = $('#myTable thead th').eq($(this).index()).text();
                $(this).html('<input type="text" placeholder="Search ' + title + '" />');
            });

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

            table.columns().every(function () {
                var that = this;

                $('input', this.footer()).on('keyup change', function () {
                    that
                        .search(this.value)
                        .draw();
                });
            });
            
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

@using (@Html.BeginForm("Salvar", "AcompanhamentoEntrega", FormMethod.Post)) {
<div id="tabelaFenix">
  <table id="myTable" class="stripe table compact hover" cellspacing="0">
    <thead style="position:static">
      <tr>
        <th align="left" style="font-size:10px">DATA EXPEDIÇÃO</th>
        <th align="left" style="font-size:10px">STATUS ENTREGA</th>
        <th align="left" style="font-size:10px">DATA ENTREGA</th>
        <th align="left" style="font-size:10px">CONFIRMACAO</th>
      </tr>
    </thead>
    <tbody>
      @for (int i = 0; i
      < Model.listaEntrega.Count(); i++) { <tr>
        <td height="2px"> @Html.TextBoxFor(m => m.listaEntrega[i].data_expedicao, new { @readonly = "readonly", @size = "4px", @class = "form-controldata_expedicao" })</td>
        <td height="2px"> @Html.TextBoxFor(m => m.listaEntrega[i].status_entrega, new { @readonly = "readonly", @size = "4px", @class = "form-controldata_expedicao" })</td>
        <td height="2px"> @Html.TextBoxFor(m => m.listaEntrega[i].data_entrega, new { @readonly = "readonly", @size = "10px", @class = "form-controldata_expedicao" }) </td>
        <td height="2px"> @Html.TextBoxFor(m => m.listaEntrega[i].confirmacao, new { @readonly = "readonly", @size = "18px", @class = "form-controldata_expedicao" }) </td>
        </tr>
        }
    </tbody>
    <tfoot>
      <tr>
        <th>DATA EXPEDIÇÃO</th>
        <th>STATUS ENTREGA</th>
        <th>DATA ENTREGA</th>
        <th>CONFIRMACAO</th>
      </tr>
    </tfoot>
  </table>
</div>
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.