2

Estou com um problema ao utilizar o plugin do datatables column filter, o mesmo não me reporta erro mas também não gera os filtros, segue meu código:

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

minha tabela:

 @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>
            }

Meus imports:

<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
8
  • Gerar os filtros, que você diz, é relativo às colunas que não aparecem as opções de filtragem, certo? 20/08/2015 às 14:26
  • isso mesmo, este filtro deveria gerar um filtro por coluna, mas ele não esta gerando, e nem me devolve um erro por debug
    – Jeff Silva
    20/08/2015 às 14:32
  • Já tentou inspecionar a página pra ver se não houve algum erro com o Datatables? 20/08/2015 às 14:34
  • Sim, o unico erro que deu é por eu ter tentado iniciar duas vezes, porém tirei a função que traduz e não devolve nenhum tipo de erro.
    – Jeff Silva
    20/08/2015 às 14:36
  • No seu lugar, eu voltaria um pouco atrás nos tutoriais do Datatables e colocaria o filtro mais simples possível. 20/08/2015 às 14:38

2 Respostas 2

2

Por padrão, o dataTables possui um filtro global, onde ele filtra os dados de todos os elementos da tabela. Pela sua pergunta você está querendo um filtro em cada coluna. Para isso, basta modificar a fim de adicionar um input em cada header, para realizar a busca, Ficaria assim o seu código:

    // 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;
    }
}

Você pode ver um exemplo funcional no JsFiddle.

Resposta retirada com base no forum do dataTables.

1
  • Os filtros ainda não aparecem, apesar da página em si não devolver nenhum erro no navegador.
    – Jeff Silva
    20/08/2015 às 15:16
0

Meio atrasado (só 4 anos), mas estou respondendo para server de referência para quem teve este problema.

O autor da pergunta está tentando executar a função no elemento footer da tabela sendo que o mesmo não existe.

Além disso, o código também requer o id correto no Js.

O código abaixo deve funcionar no 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>
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .