Como agregar un thead de busqueda en un datatable llenado con Ajax

Como agregar un thead de busqueda en un datatable llenado con Ajax

Jeff-1Jeff-1 Posts: 1Questions: 1Answers: 0

$('#dtListofUsers thead tr').clone(true).appendTo('#dtListofUsers thead');
$('#dtListofUsers thead tr:eq(1) th').each(function (i) {
var title = $(this).text();
$(this).html('<input type="text" class="form-control form-control-sm" placeholder="Buscar ' + title + '" />');

            $('input', this).on('keyup change', function () {
                if (table.column(i).search() !== this.value) {
                    table
                        .column(i)
                        .search(this.value)
                        .draw();
                }
            });
        });
        var columnSet = [
            {
                title: "Id usuario",
                id: "userId",
                data: "userId",
                "visible": false,
                "searchable": false
            },
            {
                title: "Nombre de usuario",
                id: "userName",
                data: "userName",
            },
            {
                title: "Correo electrónico",
                id: "userEmail",
                data: "userEmail",
            },
            {
                title: "Roles del usuario",
                id: "roleUsername",
                data: "roleUsername",
                "visible": false,
                "searchable": false
            },
            {
                title: "Estado",
                id: "estadoUser",
                data: "estadoUser",
            },
            {
                title: "Controles",
                id: "Control",
            },
            ]

                 //inicia datatable
        var table = $("#dtListofUsers").DataTable({
            //destroy: true,
            dom:
                "<'row mb-3'<'col-sm-12 col-md-6 d-flex align-items-center justify-content-start'f><'col-sm-12 col-md-6 d-flex align-items-center justify-content-end'lB>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
            "ajax": {
                "url": "@ViewBag.Path/api/auth/GetListUser",
                "type": "GET",
                "dataSrc": "",
                "contentType": "aplication/json; charset=utf-8",
                "dataType": "json",
                headers: {
                    'Authorization': 'Bearer ' + Token
                }
            },
            columns: columnSet,
            buttons: [
                {
                    text: '<i class="fal fa-sync mr-1"></i>',
                    className: 'btn-primary btn-sm',
                    action: function (e, dt, node, config) {

                        //reloadDT();
                        if (!($('#dtListofUsers').DataTable().data().any())) {
                            //console.log("Está vacia la tabla");
                            //$("#ddlCambiarEstadoCorte").hide();
                        }
                        else {
                            //console.log("No está vacia");
                            $('#dtListofUsers').DataTable().ajax.reload();
                        }
                    }
                },
                {
                    extend: 'pdfHtml5',
                    text: 'PDF',
                    titleAttr: 'Generar PDF',
                    className: 'btn-outline-danger btn-sm mr-1'
                },
                {
                    extend: 'excelHtml5',
                    text: 'Excel',
                    titleAttr: 'Generar Excel',
                    className: 'btn-outline-success btn-sm mr-1'
                },
                {
                    extend: 'csvHtml5',
                    text: 'CSV',
                    titleAttr: 'Generar CSV',
                    className: 'btn-outline-primary btn-sm mr-1'
                },
                {
                    extend: 'copyHtml5',
                    text: 'Copy',
                    titleAttr: 'Copiar al portapapeles',
                    className: 'btn-outline-primary btn-sm mr-1'
                },
                {
                    extend: 'print',
                    text: 'Print',
                    titleAttr: 'Imprimir tabla',
                    className: 'btn-outline-primary btn-sm'
                }
            ],
            responsive: true,
            fixedHeader: true,
            paging: true,
            scrollX: true,
            scrollY: true,
            columnDefs: [
                {
                    targets: -1,
                    title: 'Controles',
                    orderable: false,
                    render: function (data, type, full, meta) {
                        return "\n\t\t\t\t\t\t<div class='d-flex demo'>\n\t\t\t\t\t\t\t<div class='dropdown d-inline-block'>\n\t\t\t\t\t\t\t\t<a href='#' class='btn btn-sm btn-outline-primary btn-icon' data-toggle='dropdown' aria-expanded='true' title='More options'><i class=\"fal fa-plus\"></i></a>\n\t\t\t\t\t\t\t\t<div class='dropdown-menu'>\n\t\t\t\t\t\t\t\t\t<a class='dropdown-item' href='javascript:void(0);'>Cambiar Estado</a>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>";
                    },
                },
                {
                    targets: 4,
                    /*  The `data` parameter refers to the data for the cell (defined by the
                        `data` option, which defaults to the column being worked with, in this case `data: 16`.*/
                    render: function (data, type, full, meta) {
                        var badge = {
                            'true':
                            {
                                'title': 'Activo',
                                'class': 'badge-success'
                            },
                            'false':
                            {
                                'title': 'Inactivo',
                                'class': 'badge-secondary'
                            },
                        };
                        if (typeof badge[data] === 'undefined') {
                            return data;
                        }
                        return '<span class="badge ' + badge[data].class + ' badge-pill">' + badge[data].title + '</span>';
                    },
                }]

            , "language": {
                "sSearchPlaceholder": "Buscar"
                , "sProcessing": "Procesando..."
                , "sLengthMenu": "Mostrar _MENU_ registros"
                , "sZeroRecords": "No se encontraron resultados"
                , "sEmptyTable": "Ningún dato disponible en esta tabla"
                , "sInfo": "Mostrando del _START_ al _END_ de un total de _TOTAL_ registros"
                , "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros"
                , "sInfoFiltered": "(filtrando de un total de _MAX_ registros)"
                , "sInfoPostFix": ""
                , "sSearch": "Buscar:"
                , "sUrl": ""
                , "sInfoThousands": ","
                , "sLoadingRecords": "Cargando..."
                , "oPaginate": {
                    "sFirst": "Primero"
                    , "sLast": "Último"
                    , "sNext": "Siguiente"
                    , "sPrevious": "Anterior"
                }
            }
        });

Answers

  • colincolin Posts: 15,237Questions: 1Answers: 2,598

    This example should help. It's showing Ajax data with column filters. Could you look at that, please, and see if it helps. If it's still not working for you, please can you update my example, or link to your page, so that we can see the problem.

    Cheers,

    Colin

This discussion has been closed.