Soma valores selecionados através de checkboxes

1,169 views
Skip to first unread message

Tecsite Estúdio Digital - Santos/SP

unread,
Jun 17, 2009, 8:26:44 AM6/17/09
to jque...@googlegroups.com
Gente, to precisando de um help.

EU achei o codigo abaixo, mas precisava adapta-lo um pouquinho:

<script type="text/javascript">
	function checkTotal() {
		document.listForm.total.value = '';
		var sum = 0;
		for (i=0;i<document.listForm.choice.length;i++) {
		  if (document.listForm.choice[i].checked) {
		  	sum = sum + parseInt(document.listForm.choice[i].value);
		  }
		}
		document.listForm.total.value = sum;
	}
</script>

<form name="listForm">
<input type="checkbox" name="choice" value="2" onchange="checkTotal()"/>2<br/>
<input type="checkbox" name="choice" value="5" onchange="checkTotal()"/>5<br/>
<input type="checkbox" name="choice" value="10" onchange="checkTotal()"/>10<br/>
<input type="checkbox" name="choice" value="20" onchange="checkTotal()"/>20<br/>
Total: <input type="text" size="2" name="total" value="0"/>
</form>


1) Como escrever o código acima em jQuery?
2) No meu caso, eu não terei o campo TOTAL para mostrar a soma .... Será apenas uma célula de uma tabela (tem como??)


Desde ja agradeço aos que puderem me ajudar.

Beijokassss


Drika



--
Miriam de Paula

Desenvolvimento Web
Webstandard/ PHP/ MySQL/ Wordpress
www.tecsite.com.br

MSN: tecsite [at] hotmail.com
Skype: tecsite_suporte
GTalk/ GMail: tecsite [at] gmail.com
Twitter: @tecsiteweb / @miriamdepaula
----------------------------------------------------------

Ruan Carlos

unread,
Jun 17, 2009, 8:41:32 AM6/17/09
to jque...@googlegroups.com
<script type="text/javascript">
    function checkTotal() {
                var sun = 0;
                $("listForm:checked").each(
                    function(sun) {
                       sun = sun + this.value;
                        //ou this.val() não lembro
                    }
                }
                $("#total").val(sun);
                // ou $("#total").text(sun);
    }
</script>


2009/6/17 Tecsite Estúdio Digital - Santos/SP <tec...@gmail.com>



--
-----------------------------------------------------------------
Ruan Carlos
@ruanltbg
www.ruancarlos.com.br
Desenvolvedor web

Ruan Carlos

unread,
Jun 17, 2009, 8:41:59 AM6/17/09
to jque...@googlegroups.com

Ricardo

unread,
Jun 18, 2009, 2:06:50 PM6/18/09
to jQuery (Brasil)
Acho que não pode passar o parâmetro com o mesmo nome (sun) pra função
do each, senão não vai acessar a variavel 'externa', por causa do
escopo. E o ideal seria adicionar o evento via javascript (e também
usar <label> mas aí já não tem a ver com o js):

<form name="listForm" id="listForm">
<input type="checkbox" name="choice" value="2" />2<br/>
<input type="checkbox" name="choice" value="5" />5<br/>
<input type="checkbox" name="choice" value="10" />10<br/>
<input type="checkbox" name="choice" value="20" />20<br/>
Total: <input type="text" size="2" name="total" id="total" value="0"/
>
</form>

$(document).ready(){
//....
var $total = $('#total'), val, $cb = $total.find(':checkbox');
$cb.onchange(function(){
var soma = 0;
$cb.each(function(){
if (this.checked)
soma += +$(this).val();
});
$total.val( soma );
});
});

outro jeito de se fazer:

var $total = $('#total'), $form = $('#listForm');
$form[0].reset(); //evitar autocomplete do browser

$form.find(':checkbox').change(function(){
var valor = $(this).val();
$total.val( +$total.val() + (this.checked ? +valor : -valor) );
});

On 17 jun, 09:41, Ruan Carlos <ruanl...@gmail.com> wrote:
> <script type="text/javascript">
>     function checkTotal() {
>                 var sun = 0;
>                 $("listForm:checked").each(
>                     function(sun) {
>                        sun = sun + this.value;
>                         //ou this.val() não lembro
>                     }
>                 }
>                 $("#total").val(sun);
>                 // ou $("#total").text(sun);
>     }
> </script>
>
> 2009/6/17 Tecsite Estúdio Digital - Santos/SP <tecs...@gmail.com>

Juarez Gonçalves Nery Junior

unread,
Jun 18, 2009, 2:58:58 PM6/18/09
to jque...@googlegroups.com

Carlos Roberto Gomes Junior

unread,
Jun 18, 2009, 10:44:13 PM6/18/09
to jque...@googlegroups.com
De uma maneira bem simples:

$("input:name='choice").click(function(){
  total = 0;
  $(this).each(function(){
    this.checked?total+=$(this).val():null;
  });
  $("input:name='total").val(total);
});

2009/6/17 Tecsite Estúdio Digital - Santos/SP <tec...@gmail.com>
Gente, to precisando de um help.



--
-------Carlos Roberto Gomes Junior--------
---------ca...@gmail.com------------
Técnico em Informática - Web Designer
-----------www.crgdesign.com.br--------------

Jean

unread,
Jun 19, 2009, 7:55:47 AM6/19/09
to jque...@googlegroups.com
Olha soh naum conhecia essa sintaxe
input:name='choice' faz tempo q ja rola usar assim?

eh q pa mim sempre foi o input[name='choice']

soh queria tirar essa duvida ;p

2009/6/18 Carlos Roberto Gomes Junior <carlos...@gmail.com>



--
[]´s Jean a.k.a Suissa

Tecnólogo em Análise de Sistemas - UTF-PR
131

www.twitter.com/suissacorp

Stephan A. de Souza

unread,
Jun 19, 2009, 8:17:16 AM6/19/09
to jque...@googlegroups.com
Pois é, também havia estranho pois seria input[attrib="value"] e não como input:attrib="value", quando tiver tempim dou uma testada no 1.2.6. :s

Se o cara tiver mts checks ele vai ter que passar muito tempo procurando no caso do Carlos, dei uma refinada para só me trazer os selecionados (checked):

$("input[name='choice"]).click(function(){
    total = 0;
    $("input[name='choice"]:checked").each(function(){
        total+=parseInt($(this).val());
        return false;
        });
    $("input#total").val(total); //Na verdade prefiro aqui $("input#total") no lugar de $("input[name='total]")
    return false;
});

Valendo lembrar do comentário quando vai definir total

2009/6/19 Jean <jnasc...@gmail.com>



--
Programador PHP Ação Direta : www.acaodireta.com.br | p...@acaodireta.com.br
www.twitter.com/bladed
Administrador HxBr.net
Forum/TeamSpeak Admin ragnaBR.net

Stephan A. de Souza

unread,
Jun 19, 2009, 8:19:46 AM6/19/09
to jque...@googlegroups.com
Opa sabia que tinha algo errado... --'

Correções:


$("input[name='choice']").click(function(){
    total = 0;
    $("input[name='choice']:checked").each(function(){
        total+=parseInt($(this).val());
        return false;
    });
    $("input#total").val(total); //Na verdade prefiro aqui $("input#total") no lugar de $("input[name='total]")
    return false;
});

2009/6/19 Stephan A. de Souza <bla...@gmail.com>

Jean

unread,
Jun 19, 2009, 8:24:56 AM6/19/09
to jque...@googlegroups.com

    $("input#total").val(total); //Na verdade prefiro aqui $("input#total") no lugar de $("input[name='total]")

concordo completamente, alias mto raramente uso o name para usar o element, ID RULEZ!

Juarez Gonçalves Nery Junior

unread,
Jun 19, 2009, 10:06:44 AM6/19/09
to jque...@googlegroups.com
Vamos usar as boas práticas :)

getElementsByName é mais rápido

[s]

2009/6/19 Jean <jnasc...@gmail.com>

Juarez Gonçalves Nery Junior

unread,
Jun 19, 2009, 10:06:44 AM6/19/09
to jque...@googlegroups.com
Vamos usar as boas práticas :)

getElementsByName é mais rápido

[s]

2009/6/19 Jean <jnasc...@gmail.com>

Carlos Roberto Gomes Junior

unread,
Jun 19, 2009, 7:17:59 PM6/19/09
to jque...@googlegroups.com
Foi mal pessoal, erro de digitação!

Jean

unread,
Jun 22, 2009, 2:03:10 AM6/22/09
to jque...@googlegroups.com
nao sabia disso.

2009/6/19 Juarez Gonçalves Nery Junior <juarez...@gmail.com>
Reply all
Reply to author
Forward
0 new messages