2

I want to get the total value of all checked checkboxes. What i've tried is this:

$("input[type=checkbox]:checked").each(function() {
            total_modules += parseFloat($(this).val());
        });
        $("#total_modules").text(total_modules.toFixed(2));

This didn't work.

I hope someone can help me.

Thanks in advance!

PS: I fixed it, this is my new code:

function calculation()
    {
    $("input[type=checkbox]:checked").each(function() {
            total_modules += parseFloat($(this).val());
        });
        $("#total_modules").text(total_modules.toFixed(2)); 
    }
    calculation();

    $("input[type=checkbox]").click(function()
    {
        calculation();
    });

Thank you all

Leon van der Veen
  • 1,652
  • 11
  • 42
  • 60

6 Answers6

0

You can do $("input[type=checkbox]:checked").length to get the number of checked checkboxes.

Check out this jsFiddle

dknaack
  • 60,192
  • 27
  • 155
  • 202
0

its very simple use

 $("input[type=checkbox]:checked").length;

refer http://www.codeunit.co.za/2010/08/18/jquery-count-number-of-checkboxes-checked-on-a-page/

Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
0

use the length property

var checkcount = $(":checkbox:checked").length;
Pradeep Singh
  • 3,582
  • 3
  • 29
  • 42
0

The below code should work with jQuery version 1.7.1

JQUERY

$("#test").click(function() {
var tot = 0;
    $.each($("input[type=checkbox]:checked"), function (k, v){
    var val =parseFloat($(this).val());
    tot = parseFloat(tot + val);   
    })
        alert(tot);
});

HTML

<input type="checkbox" value ="10.2"/>
<input type="checkbox" value ="10.2"/>
<input type="checkbox" value ="10.2"/>
<input type="checkbox" value ="10.2"/>

<input type="buttoN" id="test" value="click me"/>
Murtaza
  • 3,045
  • 2
  • 25
  • 39
0

You can do something like

$(function(){
    var checkboxes = $("input:checkbox");
    checkboxes.change(function(){
        var total = 0.0;

        checkboxes.filter(":checked").each(function(){
            total += parseFloat(this.value);
        });

        alert (total)
    });
});

See a working demo

rahul
  • 184,426
  • 49
  • 232
  • 263
-1

Could it be that the decimal separator is incorrect? I think it needs to be a . for parseFloat to work correctly.

You also need to check if the parsed value is a number with

isNaN(parsedValue)
Grumsh
  • 139
  • 6