How to add the dynamically generated checkbox values, jquery?

2

Good morning. Currently I generate a list dynamically in which each record has its checkbox, I am trying to add the value of the class cod_cupon

var cupones_bienvenida = $('#cupones_bienvenida');
                        var tipoCupon ='';

                        $.each(response.data, function (i) {
                            if (response.data[i].Tipo_cupon == 1){
                                tipoCupon = "Cupón de 60%";
                            }
                            else if(response.data[i].Tipo_cupon == 2){
                                tipoCupon = "Cupón de 80%";
                            }
                            else{
                                tipoCupon = "Cupón de 100%";
                            }


                              $('<tr class="cupones"/>')
                                    .append($('<td/>').addClass('nuevo-td')
                                        .append($('<label/>').addClass('label-checkbox item-content').text(response.data[i].Nombre)))
                                    .append($('<td/>').addClass('label-cell nuevo-td').text(tipoCupon))
                                    .append('<div class="cod_cupon" style="display:none">' + response.data[i].Identificador + '</div>')
                                    .append($('<td/>').addClass('label-cell nuevo-td')
                                                .append($('<label/>').addClass('label-checkbox item-content')
                                                            .append('<input type="checkbox" name="cupon_check" class="cupon_check" value="' + response.data[i].Identificador + '"/>')
                                                            .append($('<span/>').addClass('item-media').append('<i class="icon icon-form-checkbox"></i>'))))
                                    .appendTo(cupones_bienvenida);

In the following way I realize the counter when selecting the checkbox, but when I deselect the checkbox it does not subtract it, that is, if I have two checkboxes selected, the result should be 2, but if I deselect 1, I would only have 1 checkbox selected so the value would have to print 1.

var total = 0;
    $('#cupones_bienvenida').on('click','.cupon_check', function(e){
        console.log("SELECIONO checkbox");
        total++;
        console.log(total);
    });
    
asked by JG_GJ 21.09.2018 в 16:39
source

1 answer

2

Try this code

var total = 0;
    $('#cupones_bienvenida').on('click','.cupon_check', function(e){
        if($(this).is(':checked')) {
            total++;
        }
        else{
            total--;
        }
        console.log(total);
    }); 
    
answered by 21.09.2018 / 16:57
source