cálculos na tabela(html)

2,177 views
Skip to first unread message

Diego Nogueira

unread,
Jun 18, 2009, 7:48:18 AM6/18/09
to jque...@googlegroups.com
Bom dia galera!

estou procurando na net, mas ainda não achei...
alguém sabe se existe algum plugin para jquery que faça calculos, tipo, totais, subtotais, descontos, soma de colunas, de linhas etc..???

agradeço a atenção de todos.
abraços

--
Atenciosamente,

Diego Nogueira
Blog: http://diegonogueira.wordpress.com
Site: http://www.d3i.com.br
Msn: noguei...@hotmail.com

Morcego

unread,
Jun 18, 2009, 8:12:13 AM6/18/09
to jque...@googlegroups.com
Olá Diego, eu nunca precisei utilizar isso, mas em uma pesquisa rápida
pelo google encontrei esse link[1], acho que a partir daí da pra
resolver os outros problemas.

Atenciosamente,
Caio Fernandes

[1] http://www.endusersharepoint.com/?p=1106

2009/6/18 Diego Nogueira <diegoalvar...@gmail.com>:

Rodrigo Corrêa e Castro

unread,
Jun 18, 2009, 8:12:35 AM6/18/09
to jque...@googlegroups.com
Diego,


Vê se esse lhe ajuda.


Abs



2009/6/18 Diego Nogueira <diegoalvar...@gmail.com>



--
_________________________________
Rodrigo Corrêa e Castro
Web Developer

rodrigocor...@gmail.com
+55 24 9839-2129
+55 24 3421-1956


"ECONOMIZE PAPEL - PENSE ANTES DE IMPRIMIR!"

Tanure

unread,
Jun 19, 2009, 3:35:33 PM6/19/09
to jque...@googlegroups.com
isso é bem facil e fazer...

fiz aqui um teste, pra vc ver e se basear:

função:

o uso dela é simples... só adicionar a classe, como mostrado nop HTML, destacado em vermelho, abaixo

$(document).ready(function(){
   
    $('.somaLinha').each(function(){
        var soma = 0;
        $(this).parent('tr').children('td').not('.somaLinha').each(function(){
            soma += parseFloat( $(this).text() );
        })
        $(this).text(soma);
    });
   
    $('.somaLinhas').each(function(){
        var soma = 0;
        $('.somaLinha').each(function(){
            soma += parseFloat( $(this).text() );
        })
        $(this).text(soma);
    });
   
   
});

html:

<?php
define('BASE_SITE', 'http://localhost/testes/jquery/')
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>Teste </title>
       
        <!-- JQUERY -->
        <script type="text/javascript" src="<?php echo BASE_SITE;?>js/jquery-1.3.2.min.js" language="javascript"></script>
        <script type="text/javascript" src="<?php echo BASE_SITE;?>js/jquery-ui-1.7.1.custom.min.js" language="javascript"></script>
        <link href="<?php echo BASE_SITE;?>css/jquery-ui-1.7.1.custom.css" rel="stylesheet" type="text/css" />
           
        <!-- ESPECIFICO -->   
        <script type="text/javascript" src="<?php echo BASE_SITE;?>js/common.js" language="javascript"></script>
       
        <!-- CSS -->
        <link href="<?php echo BASE_SITE;?>css/estilo.css" rel="stylesheet" type="text/css" />
       
       


    </head>
    <body>
        <!--Site-->
        <div id="site">
            <!--container-->
            <div id="container">
               
                <table width="300" border="0" cellspacing="0" cellpadding="0" summary="sum">
                  <caption>
                    tabela
                  </caption>
                  <tr>
                    <th scope="col"></th>
                    <th scope="col">jan</th>
                    <th scope="col">fev</th>
                    <th scope="col">mar</th>
                    <th scope="col">abr</th>
                    <th scope="col">mai</th>
                    <th scope="col">jun</th>
                    <th scope="col">jul</th>
                    <th scope="col">ago</th>
                    <th scope="col">set</th>
                    <th scope="col">total</th>
                  </tr>
                  <tr>
                    <th scope="row">sem 1</th>
                    <td>10</td>
                    <td>5</td>
                    <td>63</td>
                    <td>58</td>
                    <td>85</td>
                    <td>65</td>
                    <td>12</td>
                    <td>47</td>
                    <td>52</td>
                    <td class="somaLinha"></td>
                  </tr>
                  <tr>
                    <th scope="row">sem 2</th>
                    <td>25</td>
                    <td>65</td>
                    <td>85</td>
                    <td>69</td>
                    <td>15</td>
                    <td>52</td>
                    <td>85</td>
                    <td>65</td>
                    <td>25</td>
                    <td  class="somaLinha"></td>
                  </tr>
                  <tr>
                    <th scope="row">sem 3</th>
                    <td>52</td>
                    <td>65</td>
                    <td>85</td>
                    <td>96</td>
                    <td>65</td>
                    <td>15</td>
                    <td>25</td>
                    <td>63</td>
                    <td>65</td>
                    <td  class="somaLinha"></td>
                  </tr>
                  <tr>
                    <th scope="row">sem 4</th>
                    <td>41</td>
                    <td>25</td>
                    <td>52</td>
                    <td>36</td>
                    <td>85</td>
                    <td>75</td>
                    <td>85</td>
                    <td>98</td>
                    <td>85</td>
                    <td  class="somaLinha"></td>
                  </tr>
                  <tr>
                    <th scope="row">total</th>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td  class="somaLinhas"></td>
                  </tr>
                </table>
               
            </div>
            <!--container-->
        </div>
        <!--Site-->
    </body>
</html>

Juarez Gonçalves Nery Junior

unread,
Jun 19, 2009, 4:47:43 PM6/19/09
to jque...@googlegroups.com
E a velocidade?

Este tipo de programação mata o browser.

Imagine esta tabela com umas 100 linhas!

execute com o console.time para verificar:

$(document).ready(function(){
    console.time('speed');
    $('.somaLinha').each(function(){
        var soma = 0;
        $(this).parent('tr').children('td').not('.somaLinha').each(function(){
            soma += parseFloat( $(this).text() );
        })
        $(this).text(soma);
    });
    
    $('.somaLinhas').each(function(){
        var soma = 0;
        $('.somaLinha').each(function(){
            soma += parseFloat( $(this).text() );
        })
        $(this).text(soma);
    });
    
    console.timeEnd('speed');
});

Estou comentando apenas para alertar, é uma crítica construtiva :)

Veja teu exemplo "melhorado"!


[s]

2009/6/19 Tanure <leta...@gmail.com>

Tanure

unread,
Jun 19, 2009, 5:27:42 PM6/19/09
to jque...@googlegroups.com
Vou dar uma olhada juarez

realmente, não me preocupei com performance... mas serve de desculpa, que fiz apenas pra dar o caminho pra ele? rs

eu refiz ela, antes de ver sua resposta... pra nao desperdiçar, segue:

ficou com 261ms pra uma tabela de 100 linhas.. ver se melhoro com o que ver no seu exemplo

$(document).ready(function(){
   
    jQuery.fn.extend({
        colore: function() {
            var numero = parseFloat( $(this).text() );
            if(numero < 0) $(this).css('color', 'red');
            else $(this).css('color', 'green');
        }
    });

    jQuery.fn.extend({
        somaLinhas: function() {
            $(this).children().not('caption').each(function(){
                $(this).children('tr').each(function(){
                    var soma = 0;
                    var addTd = false;
                    $(this).children('td').each(function(){
                        addTd = true;
                        $(this).colore();

                        soma += parseFloat( $(this).text() );
                    });
                    if(addTd)
                        var novaTd = $(this).append('<td>'+soma+'</td>')
                       
                });
            });
        }
});

   
   
    //uso da função
    $('#tabela').somaLinhas();
   
});

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="description" content="A Construtora Valle Ribeiro é uma empresa especializada em construção civil, obras prediais, residenciais e comerciais de luxo situada em Belo Horizonte, MG">
        <meta name="keywords" content="Construtora, Belo Horizonte, valle, vale, ribeiro, belo horizonte, minas gerais, construção , predios">
        <meta name="copyright" content="Valle Ribeiro">
        <meta name="author" content="Madri Comunicativa / Luiz Tanure">
        <meta name="email" content="leta...@gmail.com">
        <meta name="url" content="www.valleribeiro.com.br"/>
        <meta name="title" content="Construtora Valle Ribeiro"/>
        <meta name="Audience" content=" All"/>
        <meta name="Distribution" content="Global">
        <meta name="Rating" content="General">
        <meta name="Robots" content="INDEX,FOLLOW">
        <meta name="Revisit-after" content="7 Days">

        <title>Construtora Valle Ribeiro - <?php echo $titulo;?> - Belo Horizonte, Minas Gerais</title>

        <link rel="shortcut icon" href="<?php echo BASE_SITE;?>img/valle.ico" type="image/x-icon" />
        <link rel="icon" href="<?php echo BASE_SITE;?>img/valle.ico" type="image/x-icon"/>

           
        <!-- JQUERY -->
        <script type="text/javascript" src="<?php echo BASE_SITE;?>js/jquery-1.3.2.min.js" language="javascript"></script>
        <script type="text/javascript" src="<?php echo BASE_SITE;?>js/jquery-ui-1.7.1.custom.min.js" language="javascript"></script>
        <link href="<?php echo BASE_SITE;?>css/jquery-ui-1.7.1.custom.css" rel="stylesheet" type="text/css" />
       
        <!-- LIGHTBOX -->
        <script type="text/javascript" src="<?php echo BASE_SITE;?>js/jquery.lightbox-0.5.min.js" language="javascript"></script>
        <link href="<?php echo BASE_SITE;?>css/jquery.lightbox-0.5.css" rel="stylesheet" type="text/css" />

       
        <!-- ESPECIFICO -->   
        <script type="text/javascript" src="<?php echo BASE_SITE;?>js/common.js" language="javascript"></script>
       
        <!-- CSS -->
        <link href="<?php echo BASE_SITE;?>css/reset.css" rel="stylesheet" type="text/css" />
        <link href="<?php echo BASE_SITE;?>css/valle.css" rel="stylesheet" type="text/css" />

       
       


    </head>
    <body>
        <!--Site-->
        <div id="site">
            <!--container-->
            <div id="container">
                <?php include('menu_topo.php');?>
           
                <?php (isset($conteudo) ? include($conteudo) : 'Sem conteúdo') ;?>
               
                <?php include('rodape.php');?>
            </div>
            <!--container-->
        </div>
        <!--Site-->
<script type="text/javascript">
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
    try {
        var pageTracker = _gat._getTracker("UA-7662575-13");
        pageTracker._trackPageview();
    } catch(err) {}
</script>
    </body>
</html>

Tanure

unread,
Jun 19, 2009, 5:28:22 PM6/19/09
to jque...@googlegroups.com
opa.. esqueci de remover as 'meta'

sorry..
copy paste da nisso

Tanure

unread,
Jun 19, 2009, 5:29:18 PM6/19/09
to jque...@googlegroups.com
não, nao... mande errado mesmo

segue o html certo


<?php
define('BASE_SITE', 'http://localhost/testes/jquery/')
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>Teste </title>

       
        <!-- JQUERY -->
        <script type="text/javascript" src="<?php echo BASE_SITE;?>js/jquery-1.3.2.min.js" language="javascript"></script>
        <script type="text/javascript" src="<?php echo BASE_SITE;?>js/jquery-ui-1.7.1.custom.min.js" language="javascript"></script>
        <link href="<?php echo BASE_SITE;?>css/jquery-ui-1.7.1.custom.css" rel="stylesheet" type="text/css" />
           
        <!-- ESPECIFICO -->   
        <script type="text/javascript" src="<?php echo BASE_SITE;?>js/common.js" language="javascript"></script>
       
        <!-- CSS -->
        <link href="<?php echo BASE_SITE;?>css/estilo.css" rel="stylesheet" type="text/css" />

       
       


    </head>
    <body>
        <!--Site-->
        <div id="site">
            <!--container-->
            <div id="container">
               
                <table width="300" border="0" cellspacing="0" cellpadding="0" summary="sum" id="tabela">

                  <caption>
                    tabela
                  </caption>
                  <tr>
                    <th scope="col"></th>
                    <th scope="col">jan</th>
                    <th scope="col">fev</th>
                    <th scope="col">mar</th>
                    <th scope="col">abr</th>
                    <th scope="col">mai</th>
                    <th scope="col">jun</th>
                    <th scope="col">jul</th>
                    <th scope="col">ago</th>
                    <th scope="col">set</th>
                  </tr>
                  <?php for($i = 0; $i < 100; $i++): ?>
                  <tr>
                    <th scope="row">sem <?php echo $i; ?></th>
                    <td><?php echo rand(-100,100); ?></td>
                    <td><?php echo rand(-100,100); ?></td>
                    <td><?php echo rand(-100,100); ?></td>
                    <td><?php echo rand(-100,100); ?></td>
                    <td><?php echo rand(-100,100); ?></td>
                    <td><?php echo rand(-100,100); ?></td>
                    <td><?php echo rand(-100,100); ?></td>
                    <td><?php echo rand(-100,100); ?></td>
                    <td><?php echo rand(-100,100); ?></td>
                  </tr>
                  <?php endfor; ?>

Diego Nogueira

unread,
Jun 20, 2009, 10:18:02 AM6/20/09
to jQuery (Brasil)
Obrigado a todos pelas interações!

Gostaria de um outro conselho de vocês,
qual das formas devo utilizar, no meu caso não terei tabelas com 100
registros...
1)http://gist.github.com/132884
2) Tanure - 19 jun, 18:29

sei que indefere, mas gostaria de informar, esto utilizando ruby on
rails.

agradeço mais uma vez a TODOS!!!!!


abraços

De: Tanure <letan...@gmail.com>
Data: Fri, 19 Jun 2009 18:29:18 -0300
Local: Sex 19 jun 2009 18:29
Assunto: Re: [jquery-br] Re: cálculos na tabela(html)
Responder | Responder ao autor | Encaminhar | Imprimir | Mensagem
individual | Mostrar original | Denunciar esta mensagem | Localizar
mensagens deste autor

Tanure

unread,
Jun 20, 2009, 4:38:03 PM6/20/09
to jque...@googlegroups.com
Diego,

pelo teste que fiz com minha versão e a versão do Juarez, a dele é indiscutivelmente mais rápida... mas para uma tabela de 100 registros.. ou mesmo 200 é imperceptível... tanto faz vc usar uma como outra... o ideal seria vc adaptar e colocar o que vc precisa...

a dele esta mais rapida, e exige uma tabela formatada corretamente com thead, tbody e tfoot... com campos vazios para a soma das linhas e soma final...

a que fiz cria esses campos dinamicamente...

mas o que ria perguntar é.. pq vc tem necessidade de fazer isso via javascript? não é melhor executar essa soma na view, no servidor mesmo?


enfim... pra 100 linhas, tanto faz uma como a outra... se precisar de alguma ajuda, diga ai

Luiz Tanure

Ricardo

unread,
Jun 20, 2009, 5:47:43 PM6/20/09
to jQuery (Brasil)
É muito mais rápido acessar .rows e .cells direto do que buscar no
DOM, como na 1a. Eu só alteraria algumas coisas pra evitar problemas:
colocar o negrito via CSS e não usando <strong>, usar .is() ao invés
de comparar o className (pode ter outras classes), e text() no lugar
de innerHTML (mais rápido, e no caso de pegar o valor ignora outras
tags).

http://gist.github.com/133298

On 20 jun, 11:18, Diego Nogueira <diegoalvareznogue...@gmail.com>
wrote:
> Obrigado a todos pelas intera es!
>
> Gostaria de um outro conselho de voc s,
> qual das formas devo utilizar, no meu caso n o terei tabelas com 100
> registros...
> 1)http://gist.github.com/132884
> 2) Tanure - 19 jun, 18:29
>
> sei que indefere, mas gostaria de informar, esto utilizando ruby on
> rails.
>
> agrade o mais uma vez a TODOS!!!!!
>
> abra os
>
> De: Tanure <letan...@gmail.com>
> Data: Fri, 19 Jun 2009 18:29:18 -0300
> Local: Sex 19 jun 2009 18:29
> Assunto: Re: [jquery-br] Re: c lculos na tabela(html)
> Responder | Responder ao autor | Encaminhar | Imprimir | Mensagem
> individual | Mostrar original | Denunciar esta mensagem | Localizar
> mensagens deste autor
>
> On 19 jun, 18:29, Tanure <letan...@gmail.com> wrote:
>
> > n o, nao... mande errado mesmo

Nelson Cristiano Santos Jucoski

unread,
Jan 25, 2017, 1:52:39 PM1/25/17
to jQuery (Brasil), diegoalvar...@gmail.com
Boa tarde pessoal....o plugin para calculo muito bom já usei em meus projetos você encontra neste link http://www.xsanisty.com/project/calx/
e só adicionar uma classe ao campo que deseja somar ou calcular e trabalhar tranquilo como se fosse um excel....de uma olha ai se ajuda.
no site da http://plugins.jquery.com/calx/ voce tambem pode baixar e tem varias formatações para números inclusive brasileiros como moeda em real.....virgula ao invés de ponto etc....estude a documentação do plugin.....adianta um monte de tempo em programação....forte abraço.
Reply all
Reply to author
Forward
0 new messages