Solucionado (ver solução)
Solucionado
(ver solução)
5
respostas

Somar td em jquery

Boa tarde

Na tabela não consigo somar os números das tds no jquery ao clicar no botão não soma. Teria que somar R$100 +R$ 300 + R$500 = R$900.

    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">

    <title>Cadastro Usuário</title>

    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body class="posicaoForm">

<fieldset class="border p-2 borderCampos">
    <legend class="w-auto">Produtos</legend>
    <form method="post" action="" id="ajax_form">

        <table class="table">
            <thead>
                <tr>
                    <th scope="col"></th>
                    <th scope="col">Associado</th>
                    <th scope="col">Não associado</th>
                    <th scope="col">Estudante</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <th scope="row">Produto A</th>
                    <td class="valorA1">R$100</td>
                    <td class="valorA2">R$200</td>
                    <td class="valorA3">R$500</td>
                </tr>
                <tr>
                    <th scope="row">Produto B</th>
                    <td class="valorB1">R$300</td>
                    <td class="valorB2">R$400</td>
                    <td class="valorB3">R$150</td>
                </tr>
                <tr>
                    <th scope="row">Produto C</th>
                    <td class="valorC1">R$500</td>
                    <td class="valorC2">R$600</td>
                    <td class="valorC3">R$250</td>
                </tr>
            </tbody>
        </table>
        <button type="button" class='produto btn btn-primary'>Produtos Associado</button>
        <button type="button" class='produto1 btn btn-primary'>Produtos Não Associado</button>
        <button type="button" class='produto2 btn btn-primary'>Produtos Estudante</button>

    </form>
</fieldset>
<br />
<fieldset class="border p-2 borderCampos">
    <legend class="w-auto">Produtos</legend>
    <form method="post" action="" id="ajax_form">

        <table class="table">
            <thead>
                <tr>
                    <th scope="col">Associado</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><div id="resultado"></div></td>
                </tr>
                <tr>
                    <td><button type="button" class="somaAssociado btn btn-primary">Somar</button></td>
                </tr>
                <tr>
                    <td><div id="total"></div></td>
                </tr>
            </tbody>
        </table>

<script>
    $('.produto').on('click', function () {

        var lista = $('td:nth-child(2)');
        for (k=0;k<lista.length;k++){
            valor=lista[k].innerText;
            trocar = valor.replace(",", ".");

             if (lista[k].getAttribute("usado")!="sim"){
                document.querySelector("#resultado").innerHTML=document.querySelector("#resultado").innerHTML+valor+"<br>";
                lista[k].setAttribute("usado","sim");
                break;
             }

        }

    });


    $('.somaAssociado').on('click', function(){

        var valor1 = parseInt(document.getElementsByClassName(valorA1).value);
        var valor2 = parseInt(document.getElementsByClassName(valorB1).value);
        var valor3 = parseInt(document.getElementsByClassName(valorC1).value);

        var soma = valor1 +  valor2 + valor3;

        document.getElementById("total").innerHTML = soma;
    });

</script>
Aguardo a resposta Att: Cezar
5 respostas

Boa tarde, Cezar! Como vai?

Vc pode adaptar essa solução aqui ao seu código:

<div class="price">R$195.000,20</div>
<div class="price">R$21.404,00</div>
<div class="price">R$7.000,00</div>
<div class="price">R$450,00</div>
$(function() {
  var totals = $('.price');

  var sum = 0;
  for (var i = 0; i < totals.length; i++) {
    //strip out Real signs and commas
    var v = $(totals[i]).text().replace(/[^\d.]/g, '');

    //convert string to integer
    var ct = parseFloat(v);
    sum += ct;
  }

  console.log(sum);
});

Pegou a ideia? Qualquer coisa é só falar!

Grande abraço e bons estudos, meu aluno!

Olá boa noite

Está quase lá para concluir. A dúvida e a seguinte, quando click no botão da tabela aparece o valor de R$100 e assim os outros valores O que precisa que funcione, e quando ao clicar no botão soma só apareça se tem valor na div anterior que a #resultado, se não tem valor não aparecer nada, ou seja se não clicou no botão da tabela não tem valor e se clicar no soma também não terá valor a exibir. Ao clicar 1 valor clicar no soma aparece 1 valor, se clicar 2 vezes tem 2 valores somente somar os 2 valores e se clicar no 3, somar todos os valores.

    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">

    <title>Cadastro Usuário</title>

    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body class="posicaoForm">

<fieldset class="border p-2 borderCampos">
    <legend class="w-auto">Produtos</legend>
    <form method="post" action="" id="ajax_form">

        <table class="table">
            <thead>
                <tr>
                    <th scope="col"></th>
                    <th scope="col">Associado</th>
                    <th scope="col">Não associado</th>
                    <th scope="col">Estudante</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <th scope="row">Produto A</th>
                    <td class="items">R$100</td>
                    <td class="valorA2">R$200</td>
                    <td class="valorA3">R$500</td>
                </tr>
                <tr>
                    <th scope="row">Produto B</th>
                    <td class="items">R$300</td>
                    <td class="valorB2">R$400</td>
                    <td class="valorB3">R$150</td>
                </tr>
                <tr>
                    <th scope="row">Produto C</th>
                    <td class="items">R$500</td>
                    <td class="valorC2">R$600</td>
                    <td class="valorC3">R$250</td>
                </tr>
            </tbody>
        </table>
        <button type="button" class='produto btn btn-primary'>Produtos Associado</button>
        <button type="button" class='produto1 btn btn-primary'>Produtos Não Associado</button>
        <button type="button" class='produto2 btn btn-primary'>Produtos Estudante</button>

    </form>
</fieldset>
<br />
<fieldset class="border p-2 borderCampos">
    <legend class="w-auto">Produtos</legend>
    <form method="post" action="" id="ajax_form">

        <table class="table">
            <thead>
                <tr>
                    <th scope="col">Associado</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><div id="resultado"></div></td>
                </tr>
                <tr>
                    <td><button type="button" class="somaAssociado btn btn-primary">Somar</button></td>
                </tr>
                <tr>
                    <td><div id="total"></div></td>
                </tr>
            </tbody>
        </table>

    <script>
        $('.produto').on('click', function () {

            var lista = $('td:nth-child(2)');
            for (k=0;k<lista.length;k++){
                valor=lista[k].innerText;
                trocar = valor.replace(",", ".");

                 if (lista[k].getAttribute("usado")!="sim"){
                    document.querySelector("#resultado").innerHTML=document.querySelector("#resultado").innerHTML+valor+"<br>";
                    lista[k].setAttribute("usado","sim");
                    break;
                 }

            }

        });

        $('.somaAssociado').on('click', function(){
            var total = $('.items');

            var soma = 0;
            var resultado = document.querySelector("#resultado");

                if(resultado == 0) {
                    document.getElementById("total").innerHTML = "0";
                } else {
                    var valores = $(total).text().replace(/[^\d.]/g, '');
                    var valorConv = parseFloat(valores);
                    soma += valorConv;
                    document.getElementById("total").innerHTML = "R$"+soma;
                }

                /*
                 for (var i = 0; i < total.length; i++) {
                    var v = $(total[i]).text().replace(/[^\d.]/g, '');
                    var valorConv = parseFloat(valores);
                    soma += valorConv;
                    document.getElementById("total").innerHTML = "R$"+soma;
                }
                */
        });

    </script>

</body>

No aguardo da resposta. Att: Cezar

solução!

Oi Cezar tudo bem?

Veja se é isso que precisa:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">

    <title>Cadastro Usuário</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

</head>

<body class="posicaoForm">

    <fieldset class="border p-2 borderCampos">
        <legend class="w-auto">Produtos</legend>
        <form method="post" action="" id="ajax_form">

            <table class="table">
                <thead>
                    <tr>
                        <th scope="col"></th>
                        <th scope="col">Associado</th>
                        <th scope="col">Não associado</th>
                        <th scope="col">Estudante</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th scope="row">Produto A</th>
                        <td class="items">R$100</td>
                        <td class="valorA2">R$200</td>
                        <td class="valorA3">R$500</td>
                    </tr>
                    <tr>
                        <th scope="row">Produto B</th>
                        <td class="items">R$300</td>
                        <td class="valorB2">R$400</td>
                        <td class="valorB3">R$150</td>
                    </tr>
                    <tr>
                        <th scope="row">Produto C</th>
                        <td class="items">R$500</td>
                        <td class="valorC2">R$600</td>
                        <td class="valorC3">R$250</td>
                    </tr>
                </tbody>
            </table>
            <button type="button" class='produto btn btn-primary'>Produtos Associado</button>
            <button type="button" class='produto1 btn btn-primary'>Produtos Não Associado</button>
            <button type="button" class='produto2 btn btn-primary'>Produtos Estudante</button>

        </form>
    </fieldset>
    <br />
    <fieldset class="border p-2 borderCampos">
        <legend class="w-auto">Produtos</legend>
        <form method="post" action="" id="ajax_form">

            <table class="table">
                <thead>
                    <tr>
                        <th scope="col">Associado</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            <div id="resultado"></div>
                        </td>
                    </tr>
                    <tr>
                        <td><button type="button" class="somaAssociado btn btn-primary">Somar</button></td>
                    </tr>
                    <tr>
                        <td>
                            <div id="total"></div>
                        </td>
                    </tr>
                </tbody>
            </table>

            <script>
                somaAssociado=0;

                $('.produto').on('click', function () {

                    var lista = $('td:nth-child(2)');
                    for (k = 0; k < lista.length; k++) {
                        valor = lista[k].innerText;
                        trocar = valor.replace(",", ".");

                        if (lista[k].getAttribute("usado") != "sim") {
                            document.querySelector("#resultado").innerHTML = document.querySelector("#resultado").innerHTML + valor + "<br>";
                            lista[k].setAttribute("usado", "sim");
                            somaAssociado=somaAssociado*1+valor.replace("R$","")*1;
                            break;
                        }

                    }

                });

                $('.somaAssociado').on('click', function () {
                    var total = $('.items');

                    var soma = 0;
                    var resultado = document.querySelector("#resultado");

                    if (resultado == 0) {
                        document.getElementById("total").innerHTML = "0";
                    } else {
                        var valores = $(total).text().replace(/[^\d.]/g, '');
                        var valorConv = parseFloat(valores);
                        soma += valorConv;
                        document.getElementById("total").innerHTML = "R$" + somaAssociado;
                    }


                });



            </script>

</body>

Espero ter ajudado!!!

Obrigado era isso que precisava Mais se tiver dúvidas volto. Mas por hora obrigado solucionou o problema.

Disponha e bons estudos!!!