简体   繁体   中英

Javascript - How to get the sum of a checkbox group

I'm trying to get the sum of my checkbox group (from database):

<script type="text/javascript">

$.ajax({

// SOME CODE HERE

$("#permisos01Div").append("<input type='checkbox' name='chk_permisos' 
       onClick='VerCostoPermiso()' value='"+data[i].costo+"' > " + 
                                                data[i].permiso + "<br>");

// SOME CODE HERE

});

function VerCostoPermiso(){
    var group = document.getElementById('chk_permisos');
    var sum = 0.00;
    for (var i=0; i<group.length; i++){
        if (group[i].checked == true){
            sum = sum + parseFloat(group[i].value); 
        }
    }
    alert(sum);
}

</script>

The result should be: Every time i check the box, alert the sum of the total cbs checked.

My code doesn't work, i really don't know where is the problem.

Thank you for answers

It looks like your dont have an ID assigned, but your using getElementById. Try getElementsByName.

Seems you're using jQuery, you also have a name attribute, not an ID:

var sum = 0;
$(":checkbox:checked[name=chk_permisos]").each(function() {
    sum += parseFloat(this.value);
});

"chk_permisos" is the value of a name attribute and should be selected with documents.getElementsByName("chk_permisos"):

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
        function VerCostoPermiso() {
            var group = document.getElementsByName("chk_permisos");
            var sum = 0.00;
            for (var i = 0; i < group.length; i++) {
                if (group[i].checked == true) {
                    sum = sum + parseFloat(group[i].value);
                }
            }
            alert(sum);
        }
    </script>
</head>
<body>
    <div id="permisos01Div">
        <input type='checkbox' name='chk_permisos' onClick='VerCostoPermiso()' value='1'>A1<br>
        <input type='checkbox' name='chk_permisos' onClick='VerCostoPermiso()' value='10'>B10<br>
        <input type='checkbox' name='chk_permisos' onClick='VerCostoPermiso()' value='100'>C100<br>
    </div>
</body>
</html>

If there is a checkbox with out a value sometimes it has the value of "on". When you put this through the parseFloat function you get an error. I would add a number check to the if statement.

    if (group[i].checked == true && group[i].value*0 == 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM