Add checkbox with values coming from the Bank

1

I have the following code, and would like to add all the prices that are marked, but I have no idea how to do it, I hope someone helps 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>
    
asked by anonymous 04.12.2016 / 18:18

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><inputtype='checkbox'value='1'name='valores[]'><inputtype='checkbox'value='2'name='valores[]'><inputtype='checkbox'value='3'name='valores[]'><inputtype='checkbox'value='4'name='valores[]'><inputtype='checkbox'value='5'name='valores[]'><inputname="valor_total" id="valor_total">
    
21.12.2016 / 19:25