Sum checkbox with values coming from the Bank

Asked

Viewed 156 times

1

I have the following code, and I would like to add up all prices that are marked, but I have no idea how to do it, I hope someone will help me. Thank you.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>.::Lista de Produtos::.</title>
    </head>

    <body>

        <?php
        $mysqli = new mysqli('localhost', 'root', '', 'mercado');
        if (mysqli_connect_errno()) {
            echo 'Erro: ' . mysqli_connect_error();
        } else {
            $sql = 'SELECT * FROM produtos';
            echo '<fieldset>
        <legend>REGISTROS</legend><center><table style="text-align:center;">
        <thead>
            <tr>
                <th>Nome</th>
                <th>Preço</th>       
                <th>Comprar</th>                                       
            </tr>
        </thead>
        <tbody>';
            if ($result = $mysqli->query($sql)) {
                while ($row = $result->fetch_assoc()) {
                    echo '<tr>';
                    echo '<td>' . $row['nome'] . '</td>';
                    echo '<td>' . $row['preco'] . '</td>';
                    echo '<td><input type="checkbox" name="preco" value="' . $row['preco'] . '"></td>';

                    echo '</tr>';
                }
            }
            echo '</tbody>';
            echo '</table></center></fieldset>';
        }
        ?>
    </body>
</html>
  • Would you like to add ? In PHP or Javascript ?

1 answer

0

JS - jQuery

function soma(e){
  var total   = 0;
  var valores = $('input[type="checkbox"]:checked');
  $.each(valores, function(i, v){
    total = parseFloat(total) + parseFloat($(v).val());   
  });

  $("#valor_total").val(total);
}

$('input[type="checkbox"]').on('change', soma);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type='checkbox' value='1' name='valores[]'>
<input type='checkbox' value='2' name='valores[]'>
<input type='checkbox' value='3' name='valores[]'>
<input type='checkbox' value='4' name='valores[]'>
<input type='checkbox' value='5' name='valores[]'>

<input name="valor_total" id="valor_total">

Browser other questions tagged

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