How to get the value <td> of a table from another table?

Asked

Viewed 212 times

1

I have a table with checkboxs to mark and deselect the table rows.

It turns out I have another table, which is a summing up of accounts.

I want every time the user marks a checkbox, Jquery finds the corresponding td in the other table and performs the sum or subtraction operation in the correct td.

How do I get the right values? The way I did not return...

SUMMARY TABLE:

inserir a descrição da imagem aqui

HTML FROM PHP GENERATED TABLE:

<div class="col-md-8">
            <table class="table table-striped table-responsive" id="tabResumo">
                    <thead class="thead-dark">
                        <tr>
                            <th>DRE</th>
                            <th>Meta Mensal</th>
                            <th>Total Pago</th>
                            <th>Total Lançado</th>
                            <th>Saldo</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($previsaoMes as $linha): ?>
                        <?php $saldo = $linha['valor_previsto'] - ($linha['valor_pago'] + $linha['lancado']) ?>
                        <tr>
                            <td class="<?php echo $linha['nomeDRE'] ?>"><?= $linha['nomeDRE'] ?></td>
                            <td class="text-right"><?= number_format($linha['valor_previsto'], 2, ',', '.') ?></td>
                            <td class="text-right"><?= number_format($linha['valor_pago'], 2, ',', '.') ?></td>
                            <td class="text-right"><?= number_format($linha['lancado'], 2, ',', '.') ?></td>
                            <td class="text-right"><?= number_format($saldo, 2, ',', '.') ?></td>
                        </tr>   
                        <?php endforeach ?>    
                    </tbody>
            </table>
        </div>

THE OTHER TABLE WHERE I CLICK ON THE CHECKBOX:

inserir a descrição da imagem aqui

HTML OF THIS 2nd TABLE:

<div class="table-responsive">
                    <?php if (count($lista) > 0): ?>
                        <table id="tabela" class="table table-hover">
                            <thead>
                                <tr>
                                    <th>DRE</th>
                                    <th>Despesa</th>
                                    <!-- <th>#</th> -->
                                    <th>Vencimento</th>
                                    <th>Prorrogação</th>
                                    <th class="text-right">Valor</th>
                                    <th>Parcela</th>
                                    <th>Devedora</th>
                                    <th>Observação</th>
                                    <th class="text-center">Conf</th>
                                    <th>Prorrogar</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($lista as $linha): ?>
                                    <tr>
                                    <td><?= $linha['nomeDRE'] ?></td>
                                        <td><?= $linha['nomeFornecedor'] ?></td>
                                        <!-- <td><?= $linha['parcela_id'] ?></td> -->
                                        <td><?= implode("/", array_reverse(explode("-", trim($linha['data_vencimento'])))); ?></td>
                                        <td><?= implode("/", array_reverse(explode("-", trim($linha['data_prorrogacao'])))); ?></td>
                                        <td class="text-right monetary"><?= number_format($linha['valor_pagar'], 2, ',', '.') ?></td>
                                        <td class="text-center"><?= $linha['numero_parcela']."/". $linha['total_parcela'] ?></td>
                                        <td><?= $linha['nomeEmpresaDevedora'] ?></td>
                                        <td><?= $linha['observacao'] ?></td>
                                        <!--  <td><span <?php echo ($linha["status"] == 'SOLICITAR')? 
                                                'class="label label-primary"':'class="label label-default"'?>>
                                                <?php echo $linha["status"];?>
                                            </span></td> -->
                                        <td class="text-center">
                                            <div class="form-check">
                                            <label class="form-check-label">
                                                    <input class="form-check-input" type="checkbox" name="ckb[]" id="<?= $linha['parcela_id'] ?>" value="<?= $linha['parcela_id'] ?>" checked>
                                                    <span class="form-check-sign">
                                                        <span class="check"></span>
                                                    </span>
                                                </label>
                                            </div>
                                        </td>
                                        <td class="text-center">
                                            <a href="#" data-toggle="tooltip" title="Prorrogar data">
                                                <button type="button" class="btn btn-warning btn-fab btn-fab-mini js-modalData" data-toggle="modal" data-target="#modalData" onclick="pegarIdProrrogacao(<?php echo $linha['parcela_id'];?>)" aria-label="Left Align">
                                                    <i class="material-icons">date_range</i>
                                                </button>
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <strong>ATENÇÃO!</strong> Nenhuma conta encontrada.
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                    <?php endif ?>
                </div>

SCRIPT THAT TAKES THE CLICK ON THE CHECKBOX OF THE 2nd TABLE. BUT THE VALUE COMES IN WHITE AND THE EXPECTED VALUE WAS 328,964.69. THE OTHER CALCULATIONS ARE WORKING BECAUSE I HAVE CARDS THAT TOTAL:

<script>
    $(':checkbox').click(function() {
        var total = 0;
        var saldo = 0;
        var total_orcado = 0;
        var total_pago = 0;
        var total_pagar = 0;
        
        var valor = parseFloat($(this)      // Representa o elemento clicado (checkbox)
                            .closest('tr')  // Encontra o elemento pai do seletor mais próximo
                            .find('td')     // Encontra o elemento do seletor (todos os tds)
                            .eq(4)          // pega o quinto (contagem do eq inicia em 0)
                            .text()         // Retorna o texto do elemento
                            .split('.')
                            .join('')
                            .replace(',','.'));    

        // COMO EXEMPLO, AQUI ESTOU TENTANDO PEGAR O VALOR DO SALDO DO INVESTIMENTO
        var valor2 = $('#tabResumo').parent().find("INVESTIMENTO").eq(4).text();

        // AQUI EU MOSTRO O VALOR RETORNADO COM O ALERT, MAS VEM EM BRANCO
        alert("VALOR SALDO RESUMO DE INVESTIMENTO: "+valor2);
        
        total = parseFloat($('#total_a_pagar').val().split('.').join('').replace(',','.'));
            
        saldo = parseFloat($('#saldo').val().split('.').join('').replace(',','.'));

        //Chama a função com click em qualquer checkbox
        //Se o checkbox for marcado ele soma. Se não, subtrai.
        if ($(this).is(":checked")) {
            saldo += valor;
            total += valor;
        } else {
            saldo -= valor;
            total -= valor;
        }
        //Atribui o valor ao input
        $('#total_a_pagar').val(total.toLocaleString('pt-br', {minimumFractionDigits: 2})) || 0;
        $('#saldo').val(saldo.toLocaleString('pt-br', {minimumFractionDigits: 2})) || 0;
    });
</script>

1 answer

0

Comments on your code:

$('#tabResumo').parent().find("INVESTIMENTO").eq(4).text();

You are trying to find an html element named "INVESTMENT", ie . What does not exist. Most likely you are looking for a class with that name, but I didn’t find this word in your code, I don’t know if you are putting via PHP. If it’s really a class you need to use it that way:

$('#tabResumo').parent().find(".INVESTIMENTO").eq(4).text();

One tip I’d give you is: work with identifiers on both tables to facilitate relationships and find the value you need.

An example would be to assign the class "value" in the cell that contains the values and use a simpler jquery selector to find it.

There are also much more secure and consistent ways to find a value instead of . eq()

  • Thanks for the tips, I will search. Abs

Browser other questions tagged

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