1

Quiero agregar un checkTodo que marque todas las filas de un datatable. Cada fila tiene su propio checkbox que se renderiza de acuerdo a un atributo llamado 'seleccionable'. Por el momento logre totalizar la cantidad de comprobante seleccionables y la sumatoria de los montos pero me falta localizar el check individual para poder marcarlo y agregarle la clase 'selected' a las filas correspondientes.

Dejo mi código a ver si alguien puede ayudarme

function obtener_comprobantes_actualizados(idcuenta, ids, ids2, ids3) {
    var cant = 0;
    var monto = 0;
    $("#pnlDeuda").show();

    $.ajax({
        type: "POST",
        dataType: "json",
        url: "obtenerDeuda",
        data: { 'idCuenta': idcuenta, 'idSubsistema': ids, 'idSubsistema2': ids2, 'idSubsistema3': ids3 },
        success: function (data) {

            var dataTableVariable = $("#tbComp").DataTable({
                "footerCallback": function (row, data, start, end, display) {
                    var api = this.api(), data;

                    var intVal = function (i) {
                        return typeof i === 'string' ?
                            i.replace(/[\$,]/g, '') * 1 :
                            typeof i === 'number' ?
                            i : 0;
                    };

                    total = api
                        .column(6)
                        .data()
                        .reduce(function (a, b) {
                            return intVal(a) + intVal(b);
                        }, 0);

                    $("#deudaTotal").text("Deuda Total $ " + total);
                },
                "lengthMenu": [[10, 15], [10, 15]],
                "searching": false,
                destroy: true,
                data: data,
                columns: [
                    { 'data': 'idComprobante' },
                    {
                        'data': "seleccionable",
                        "searchable": false,
                        "orderable": false,
                        "render": function (data, type, row) {
                            if (data === 1) {
                                return '<input type="checkbox" id="chkFila" />';
                            } else {
                                return '';
                            }
                        }
                    },
                    { 'data': 'ano' },
                    { 'data': 'cuota' },
                    { 'data': 'fecVtoForm' },
                    { 'data': 'dsEstadoComp' },
                    { 'data': 'totalActual' },
                ],
                columnDefs: [
            {
                "targets": [0],
                "visible": false,
            }],
                "language": { "sUrl": "fonts/datatable_espanol.txt" }
            });
            bServerSide: true;
            bProcessing: true;

            $('#tbComp tbody').off('click');
            $('#tbComp tbody').on('click', 'tr', function () {
                $("#frmpago").hide();
                let sel = dataTableVariable.row(this).data().seleccionable;
                let ch = $(this).find("#chkFila");

                if (sel == 0) {
                    alertify.error("Comprobante no seleccionable");
                } else {
                    let imp_comp = dataTableVariable.row(this).data().totalActual;

                    if ($(this).hasClass('selected')) {
                        $(this).removeClass('selected');
                        monto -= parseFloat(imp_comp);
                        $("#monto").html("Monto a pagar $ " + monto.toFixed(2));
                        cant -= 1;
                        $("#cant").html("Comprobantes Seleccionados: " + cant);
                        ch.prop('checked', false);
                    }
                    else {
                        $(this).addClass('selected');
                        monto += parseFloat(imp_comp);
                        $("#monto").html("Monto a pagar $ " + monto.toFixed(2));
                        cant += 1;
                        $("#cant").html("Comprobantes Seleccionados: " + cant);
                        ch.prop('checked', true);
                    }
                }
            });

            $('#chkTodo').change(function () {
                monto = 0;
                cant = 0;

                if ($(this).is(':checked')) {
                    var data = dataTableVariable.rows().data();

                    data.each(function (value, index) {
                        if (value.seleccionable === 1) {
                            monto += value.totalActual;
                            cant++;
                            // check checkbox y addClass('selected')
                        }
                    });
                }

                if (cant > 0) {
                    $("#monto").html("Monto a pagar $ " + monto.toFixed(2));
                    $("#cant").html("Comprobantes Seleccionados: " + cant);
                } else {
                    $("#monto").html("");
                    $("#cant").html("");
                }
            })

        }, error: function () {
            alertify.alert("Ha ocurrido un problema")
        }
    })
}

2 respuestas 2

1

Ponle a tus input checkbox una clase y en el evento click sobre el input "checkTodo", seleccionado todos los checkbox con dicha clase.

$(document).ready(function(){+

  $('#checkTodo').click(function(){
    $('.checkbox').prop('checked',true);
  });


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkTodo">

<br>
<input type="checkbox" class="checkbox" value="chek_1">
<input type="checkbox" class="checkbox" value="chek_2">
<input type="checkbox" class="checkbox" value="chek_3">
<input type="checkbox" class="checkbox" value="chek_4">

1
  • Necesito pintar las filas (addClass('selected')) por ende ese codigo no me serviria. Muchas Gracias de todas formas. Te invito a inspeccionar el codigo que acabo de publicar como respuesta
    – DavidC
    el 17 dic. 2018 a las 15:07
1

Al final use el siguiente codigo, el propuesto por cooper no me servia porque necesitaba pintar las filas seleccionables

$('#chkTodo').change(function () {
            monto = 0;
            cant = 0;

            if ($(this).is(':checked')) {
                $('#tbComp tbody tr').each(function () {
                    let sel = dataTableVariable.row(this).data().seleccionable;

                    if (sel == 1) {
                        $(this).addClass('selected');
                        let ch = $(this).find("#chkFila");
                        ch.prop('checked', true);
                        let amount = dataTableVariable.row(this).data().totalActual;
                        cant++;
                        monto += amount;
                    }
                });
            } else {
                $('#tbComp tbody tr').each(function () {
                    $(this).removeClass('selected');
                    let ch = $(this).find("#chkFila");
                    ch.prop('checked', false);
                });
            }

            totalizar();
        })

        function totalizar() {
            if (cant > 0) {
                $("#monto").html("Monto a pagar $ " + monto.toFixed(2));
                $("#cant").html("Comprobantes Seleccionados: " + cant);
            } else {
                $("#monto").html("");
                $("#cant").html("");
            }
        }

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.