Capture values after an input checkbox

Asked

Viewed 1,774 times

3

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

Segue imagem

Currently I can get the id of each checkbox selected, put in an array and print this array, but that’s not my goal. I would like for each selected checkbox to capture the service value and increment in the 'Total' input'.

My form code looks like this:

                    <?php  foreach($servicos as  $servico): ?>

                        <label class="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 catch code is like this:

<script>

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

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

    });

});

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: https://jsfiddle.net/vc6m4wvt/

In that way with $(":checkbox:checked") you get the checkbox selected (you can adapt this selector better but without seeing your HTML I let it look like this), then convert to a native array with .get() and use the method .reduce() to add it all up. This way no matter how many elements you have. I use the Number() to convert the .value that returns a String in Type: Number to be able to add.


To save both the ID (which is the input value) and also the $servico['valor'] you can put him in a field data- thus:

<?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 read it in Javascript changes 1 line relative to the code I put on top, like this:

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

jsFiddle: https://jsfiddle.net/vc6m4wvt/2/

  • 1

    Perfect Sergio, it worked here. Thank you very much for your attention and I’m sorry for disturbing you so much. = D

2

In the onchange you should walk all <inputs type="checkbox"> that are checked and increase its value in 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>
<input type="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>

  • this could make for checkbox with different Names ?

  • Yes, you can give the same class to the checkboxes you want to calculate and you only have to change to $('input.minha-class').on('change', function() { . But you don’t have to, you’re not dependent on name here, just make sure you don’t have any more chekboxes than you want to calculate. this line $('input[name="totalValor"]') is just the input where the total will be displayed

  • could you please answer my question http://answall.com/questions/178790/como-enviarcheckbox-com-names-diferentes-para-o-mysql

Browser other questions tagged

You are not signed in. Login or sign up in order to post.