Se abre y cierra (sin hacer un click) una fila en Datatables cuando se intenta expandir para visual

Se abre y cierra (sin hacer un click) una fila en Datatables cuando se intenta expandir para visual

AAlassiaAAlassia Posts: 3Questions: 1Answers: 0
edited June 19 in Free community support

Estimados buenas tardes.

Quisiera comentar un inconveniente que estoy teniendo cuando intento expandir una fila en DataTables.
En principio la aplicación, obtiene desde la base de datos solo el dato “año”, para que se muestre en el “DropDownList.” y luego de seleccionar un año en particular hacer otra búsqueda en la base de datos.

Luego, desde el JS por ajax, envío al controlador, con el año como parámetro, para seleccionar la información que luego voy a visualizar en DataTable en el html.

Cuando obtengo los datos en DataTables, puedo hacer una click en cada fila y expandir para mostrar más información.

hasta acá todo ok, el problema se presenta cuando hago una nueva selección de año, se completa el DataTables ,y en caso que quiera expandir una fila, la misma se abre y se cierra sin que haga un click para cerrarla.

Dejo el JS que estoy utilizando.

let  TablaTipoVuln;
$(document).ready(function () {

    // Evento de cambio en la DropDownList
    $("#AnioDropDown").change(function () {
        // Obtén el valor seleccionado
        var anioSeleccionado = $(this).val();
        
        // Llama a la función para actualizar DataTable con el nuevo año
        actualizarDataTable(anioSeleccionado);
    });
        
    // Configurar la DataTable
    function actualizarDataTable(anio) {

        // Guardar las filas expandidas antes de destruir la tabla
        filasExpandidas = obtenerFilasExpandidas();

        if ($.fn.DataTable.isDataTable('#DataTablesTipoVuln')) {
            // Si la tabla ya existe, limpiar y destruir
            $('#DataTablesTipoVuln').DataTable().clear().destroy();
        }

       TablaTipoVuln = $('#DataTablesTipoVuln').DataTable({

           initComplete: function () {
               // Restaurar las filas expandidas después de crear la nueva tabla
               restaurarFilasExpandidas(filasExpandidas);
           },

          //  destroy: true,
            ajax: {

                url: "/TipoVuln/TotalTipoVuln",
                type: "POST",
                data: { anio: anio },
                datatype: "json",
             },

            columnDefs: [
                {
                    width: "5%", targets: [0],
                    searchPanes: { show: false },
                },
                {
                    width: "80%", targets: [1],
                    searchPanes: { show: false },
                },
                {
                    width: "15%", targets: [2],
                    searchPanes: { show: false },
                },
             ],

            columns: [
                {
                    className: 'details-control',
                    orderable: false,
                    data: null,
                    defaultContent: '',
                },
                { data: 'vmTVulnNombre', name: 'vmTVulnNombre', autoWidth: true },
                { data: 'vmSumaTotal', name: 'vmSumaTotal', autoWidth: true },
                           ],
            scrollY: '57vh',
            scrollX: false,
            scrollCollapse: true,
            paging: false,
            ordering: false,
            searching: true,
            info: true,
            language: {
                url: "https://cdn.datatables.net/plug-ins/1.11.5/i18n/es-AR.json"
            },

            buttons: [
                {
                    extend: 'copyHtml5',
                    text: '<i class="fa fa-files-o"></i>',
                    titleAttr: 'Copiar'
                },
                {
                    extend: 'excelHtml5',
                    text: '<i class="fa fa-file-excel-o"></i>',
                    titleAttr: 'Excel'
                },
                {
                    extend: 'csvHtml5',
                    text: '<i class="fa fa-file-text-o"></i>',
                    titleAttr: 'CSV'
                },
                {
                    extend: 'pdfHtml5',
                    text: '<i class="fa fa-file-pdf-o"></i>',
                    titleAttr: 'PDF'
                },

                //  'colvis'
                {
                    extend: 'colvis',
                    text: '<i class="fa fa-columns"></i>',
                    postfixButtons: ['colvisRestore'],
                    titleAttr: 'Columna'
                }
            ],          

        });

        $('#DataTablesTipoVuln tbody').on('click', 'td.details-control', function () {

            let tr = $(this).closest('tr');
            //console.log(tr);
            let row = TablaTipoVuln.row(tr);
           // console.log(row);

                if (row.child.isShown()) {
                    // This row is already open - close it
                    $('div.slider', row.child()).slideUp(function () {
                       row.child.hide();
                       tr.removeClass('shown');
                    });

                   } else {

                    row.child(format(row.data())).show();
                    tr.addClass('shown');
                    $('div.slider', row.child()).slideDown();
                }
         });
    }


    function obtenerFilasExpandidas() {
        return $('#DataTablesTipoVuln tbody tr.shown').toArray();
    }

    function restaurarFilasExpandidas(filas) {
        filas.forEach(function (fila) {
            TablaTipoVuln.row(fila).child(format(TablaTipoVuln.row(fila).data())).show();
        });
    }
        function format(d) {
            // `d` es el objeto JSON serializado
            //var data = JSON.parse(d);

           html = '<div class="row slider p-3 j-font container">' +
                '<div class="col-sm-12 ">' +
                '<table ; background-color: #AEB6BF;">' +

                '<thead style="background-color: #FF66CC;">' +
                '<tr>' +
                '<th class="col-2">GRC</th>' +
                '<th class="col-4">Nombre</th>' +
                '<th class="col-4">Fecha</th>' +
                '<th class="col-2">Total</th>' +
                '</tr>' +
                '</thead>';

            // Iterar sobre los elementos de la lista detaTvulnAplics
            for (var i = 0; i < d.detaTvulnAplics.length; i++) {
                let item = d.detaTvulnAplics[i];
                html += '<tr>' +
                    '<td class="col-2">' + item.vmTVulnAplicGRC + '</td>' +
                    '<td class="col-4">' + item.vmTVulnAplicNombApp + '</td>' +
                    '<td class="col-4">' + item.vmTVulnAplicMesIngreso + '</td>' +
                    '<td class="col-2">' + item.vmSumaParcial + '</td>' +
                    '</tr>';
            }

            html += '</table>' +
               '</div>' +
               '</div>';

            return html;
        }
   
  
});

Muchas Gracias.!!!****

Edited by Kevin: Syntax highlighting. Details on how to highlight code using markdown can be found in this guide

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,993Questions: 26Answers: 4,887

    On line 109 you are creating the click event handler for the child rows, inside the actualizarDataTable() function. Each time you call the function you are creating an additional event handler. This is causing the child row to be shown then closed.

    Move the event handler outside the function so its initialized only once.

    Kevin

  • AAlassiaAAlassia Posts: 3Questions: 1Answers: 0

    Hola Kevin, buenas tardes.
    Moví la función que lee el evento clic, debajo de la función actualizarDataTable(),

    Ahora como resultado no expande la fila.

  • kthorngrenkthorngren Posts: 20,993Questions: 26Answers: 4,887
    Answer ✓

    I moved the function that reads the click event, below the function updateDataTable(),
    Now as a result it does not expand the row.

    Possibly you need to change the selector to something like this:

    $('#DataTablesTipoVuln').on('click', 'tbody td.details-control', function () {
    

    The tbody might not exist when the code is executed to instantiate the event handler.

    Kevin

  • AAlassiaAAlassia Posts: 3Questions: 1Answers: 0

    Thanks Kevin, with these two recommendations the application now works and the problem is solved.
    I am very grateful.

Sign In or Register to comment.