1

Tengo una consulta y es la siguiente:

Estos son los siguientes pasos de como se genera el error: Tengo un input que se ingresa "json1" y doy click al boton ejecutar json se llena el datatable con 3 registros y si selecciono un registro y doy en el boton obtener me muestra en consola el registro seleccionado por el checkbox. Luego ingreso "json2" y doy click en el boton ejecutar json se llena el datatable, pero a partir del 4to registro al seleccionar el checkbox me muestra error. Pero los 3 primeros registros no muestran error.

Codigo del Error

jquery.dataTables.min.js:116 Uncaught TypeError: Cannot read property '_aData' of undefined
    at u.<anonymous> (jquery.dataTables.min.js:116)
    at u.data (jquery.dataTables.min.js:102)
    at HTMLInputElement.<anonymous> (datatable_checkbox.html:94)
    at HTMLTableElement.dispatch (jquery.min.js:5)
    at HTMLTableElement.v.handle (jquery.min.js:5)

Mi debug señala este código

let info = dt.row($(this).closest('tr')).data();

$(document).ready(function () {
            function crearTabla(datos) {
                let $dt = $('#tbl-buys');
                let dt = $dt.DataTable({
                    processing: true,
                    serverSide: false,
                    paging: true,
                    autoWidth: false,
                    bDestroy: true,
                    data: datos,
                    order: false,
                    columns: [{
                        render: function (data, type, full, meta) {
                            // ACA controlamos la propiedad para des/marcar el input
                            return "<input type='checkbox'" + (full.checked ? ' checked' : '') + "/>";
                        },
                        orderable: false
                    },
                    {
                        data: 'Producto',
                        orderable: false
                    },
                    {
                        data: 'Cantidad',
                        orderable: false
                    },
                    {
                        data: 'Precio',
                        orderable: false
                    },
                    ]
                });
                let $total = $('#total');

                // Cuando hacen click en el checkbox del thead
                $dt.on('change', 'thead input', function (evt) {
                    let checked = this.checked;
                    let total = 0;
                    let data = [];

                    dt.data().each(function (info) {
                        // ACA cambiamos el valor de la propiedad
                        info.checked = checked;
                        // ACA accedemos a las propiedades del objeto
                        if (info.checked) total += info.Precio;
                        data.push(info);
                    });

                    dt.clear()
                        .rows.add(data)
                        .draw();
                    $total.val(total);
                });

                // Cuando hacen click en los checkbox del tbody
                $dt.on('change', 'tbody input', function () {
                let dt = $('#tbl-buys').DataTable();
                    let info = dt.row($(this).closest('tr')).data();
                    // ACA accedemos a las propiedades del objeto
                    info.checked = this.checked;

                    /**  NUEVO CÓDIGO */
                    /**  Verificar si todos están seleccionados */
                    var countSelected = 0
                    var countTotal = 0
                    dt.data().each(function (info) {
                        countTotal += 1;
                        if (info.checked) {
                            countSelected += 1;
                        }
                    });

                    /** Actualizamos UI según caso */
                    if (countSelected === countTotal) {
                        $('thead input').prop("checked", true);
                        $('thead input').prop("indeterminate", false);
                    } else if (countSelected === 0) {
                        $('thead input').prop("checked", false);
                        $('thead input').prop("indeterminate", false);
                    } else {
                        $('thead input').prop("checked", false);
                        $('thead input').prop("indeterminate", true);
                    }
                    /** END NUEVO CÓDIGO */
                });
            }

            // ACA suscribimos un listener
            $('#btnObtener').on('click', function () {
                let dt = $('#tbl-buys').DataTable();
                let checkeds = dt.data().toArray().filter((data) => data.checked);
                console.log(checkeds);
            });



            $("#boton").click(function () {
                var json = $("#idJson").val();
                if(json=="json1"){
                    crearTabla([{
                        "Producto": "Leche",
                        "Cantidad": 50,
                        "Precio": 3.20
                    },
                    {
                        "Producto": "Azucar",
                        "Cantidad": 40,
                        "Precio": 2.20
                    },
                    {
                        "Producto": "Gaseosa",
                        "Cantidad": 14,
                        "Precio": 6.50
                    }
                    ]);
                }
                if (json == "json2") {
                    crearTabla([{
                        "Producto": "Leche",
                        "Cantidad": 50,
                        "Precio": 3.20
                    },
                    {
                        "Producto": "Azucar",
                        "Cantidad": 40,
                        "Precio": 2.20
                    },
                    {
                        "Producto": "Gaseosa",
                        "Cantidad": 14,
                        "Precio": 6.50
                    },
                    {
                        "Producto": "polos",
                        "Cantidad": 2,
                        "Precio": 32.90
                    },
                    {
                        "Producto": "platos",
                        "Cantidad": 10,
                        "Precio": 2.00
                    },
                    {
                        "Producto": "tazas",
                        "Cantidad": 6,
                        "Precio": 2.50
                    },
                    {
                        "Producto": "mesas",
                        "Cantidad": 6,
                        "Precio": 150.00
                    },
                    {
                        "Producto": "televisor",
                        "Cantidad": 1,
                        "Precio": 1200.00
                    },
                    {
                        "Producto": "carne",
                        "Cantidad": 33,
                        "Precio": 15.50
                    },
                    {
                        "Producto": "Menestras",
                        "Cantidad": 54,
                        "Precio": 2.30
                    },
                    {
                        "Producto": "Paneton",
                        "Cantidad": 5,
                        "Precio": 20.50
                    },
                    {
                        "Producto": "Arroz",
                        "Cantidad": 32,
                        "Precio": 2.50
                    },
                    {
                        "Producto": "Huevos",
                        "Cantidad": 10,
                        "Precio": 3.50
                    }
                    ]);
                }

                
            });




        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" />

JSON <input type="text" id="idJson">
    <button type="button" id="boton">Ejecutar Json</button>
    <table class="table table-striped table-bordered" data-page-length="2" id="tbl-buys">
        <thead>
            <tr>
                <th>
                    <input type="checkbox" />
                </th>
                <th>Producto</th>
                <th>Cantidad</th>
                <th>Precio</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    <!--<label>Total</label>
    <input type="text" id="total" class="form-control" readonly value="0.0" />-->
    <br>
    <button id="btnObtener">Obtener</button>

2
  • El error es debido a que no coinciden el número de columnas. ¿Te aseguraste de que el json tenga las mismas propiedades?
    – farsSharp
    el 6 ene. 2020 a las 18:15
  • Tiene el mismo numero de columnas.
    – Dum
    el 6 ene. 2020 a las 19:30

1 respuesta 1

0

La respuesta era inicializar la tabla antes de este código.

var dt= $("#tabla_excel").DataTable();//Línea que soluciona el error.
let info = dt.row($(this).closest('tr')).data();

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.