Problem Counting Selected Checkboxes. PHP

Asked

Viewed 170 times

0

I have some checkbox that are a query in the BD. I need to take the selected fields and then make a division but it’s not working.

<form action="contas1.php" method="POST">

                                  <div class="form-group">
                                    <label for="Nome Conta">Nome Conta:</label>
                                    <input type="text" class="form-control" name="nome_conta">
                                  </div>

                                  <div class="form-group">
                                    <label for="Valor">Valor:</label>
                                    <input type="number" class="form-control" name="valor">
                                  </div>
                                 <!-- <button type="submit" class="btn btn-default">Adicionar Conta</button>-->

                            </div>

                            <?php
                                    include("conexao.php");
                                    $consulta = "SELECT NOME as nome,EMAIL as email FROM `usuario`";
                                    $result = mysqli_query($conexao,$consulta) or die(mysql_error());

                                     while ($membros = mysqli_fetch_array($result,MYSQLI_ASSOC))
                                    {
                                        echo '<p><input type="checkbox" name="members[]" value="' . $membros['email'] . '" /> ' . $membros['nome'] . '</p>';
                                    }

                            ?>

                            <button type="submit" class="btn btn-default">Adicionar Conta</button>

                        </form>


<?php   
include("conexao.php");

$nomeconta = $_POST['nome_conta'];
$valor = $_POST['valor'];
$email_usuario = $_COOKIE['email_usuario']; 

$valor = str_replace(',', '.', $_POST['valor']);// Troca de virgula por ponto
$contChkBox = count($_POST['members']);// Contando os membros selecionados 
$valor = round($valor / $contChkBox, 2); // Arredondando o valor e fazendo a divisão pelos os campos selecionados

$setNovaConta = atualizaConta($conexao,$_POST['nome_conta'],$_POST['valor'],$email_usuario);

function atualizaConta($conexao,$nome_conta,$valor,$email_usuario){
    try{
        $sql = "UPDATE usuario SET saldo = saldo + $valor WHERE email = '$email_usuario'";
        if (!mysqli_query($conexao,$sql)) echo "Erro ao gravar dados: " .mysqli_error($conexao);
    }catch(Exception $e){
echo "Erro no sql" .$e->getMessage();}
mysqli_close($conexao);
}

?>

1 answer

1

Use Jquery:

$('input[type=checkbox]').on('change', function () {

    var total = $('input[type=checkbox]:checked').length;   

    $('#contador').attr('data-value',total);

    $('#contador').text(total + (total > 1 ? ' selecionados' : ' selecionado'));
});

Browser other questions tagged

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