Capture values after an input checkbox

3

Good morning, I have a 'Attendance' form where there is a checkbox for each service.

CurrentlyIcangettheidofeachselectedcheckbox,putitinanarrayandprintthisarray,butthat'snotmygoal.Iwouldlikeforeachcheckedcheckboxtocapturethevalueoftheserviceandincrementinthe'Total'input.

Myformcodelookslikethis:

<?phpforeach($servicosas$servico):?><labelclass="checkbox-inline">
                            <input type="checkbox" name="servico[]"  value="<?=$servico['id']?>">
                            <?=$servico['descricao'] .' R$ ' . number_format($servico['valor'],2,',','.'); ?></label>

                        </br>
                    <?php endforeach?>

                    <h2>Total</h2>
                    <input type="number" name="totalValor" disabled>

And my checkbox id capture code looks like this:

<script>

$(document).ready(function() {
    var ids = []

    $(":checkbox").change(function () {
        if ($(this).is(":checked")) {
            ids.push($(this).val());
            $("#idServicos").text(ids);
            alert(ids);
        }

    });

});

    
asked by anonymous 29.05.2016 / 18:08

2 answers

4

You can do it like this:

$(document).ready(function() {
    $(":checkbox").change(function() {
        var total = $(":checkbox:checked").get().reduce(function(tot, el) {
            return tot + Number(el.value);
        }, 0);
        $('[name="totalValor"]').val(total);
    });
});

Example: link

In this way with $(":checkbox:checked") you will get the selected checkbox (you can adapt this selector better but without seeing your HTML, I leave it like this), then convert a native array with .get() and use the .reduce() method to add up. In this way, it does not matter when you have elements. I use Number() to convert the .value that returns a String into Type: Number to be able to do the addition.

To store both the ID (which is the value of the input) and also the $servico['valor'] you can put it in a data- field like this:

<?php  foreach($servicos as  $servico): ?>
    <label class="checkbox-inline">
        <input type="checkbox" name="servico[]"  data-valor="<?=$servico['valor']?>" value="<?=$servico['id']?>">
        <?=$servico['descricao'] .' R$ ' . number_format($servico['valor'],2,',','.'); ?></label>

and then reading this in JavaScript changes 1 line in relation to the code I put up, like this:

 return tot + Number(el.dataset.valor);

jsFiddle: link

    
29.05.2016 / 18:14
2

In onchange you should go through all% of <inputs type="checkbox"> and increase its value to the total. EXAMPLE

$('input[type="checkbox"]').on('change', function() {
   var total = 0;
   var servicos = '';
   $('input[type="checkbox"]:checked').each(function() {
      total += parseInt($(this).val());
      servicos += $(this).data('servico')+ '<br>';
   });
   $('input[name="totalValor"]').val(total);
   $('.servicos').html(servicos);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox" value="140" data-servico="dentista">140<br>
<input type="checkbox" value="130" data-servico="cardiologista">130<br>
<input type="checkbox" value="70" data-servico="oftalmologista">70<br>
<input name="totalValor" type="number">
<div class="servicos">
  
</div>
    
29.05.2016 / 18:18