Home:ALL Converter>Javascript checkbox values

Javascript checkbox values

Ask Time:2012-11-23T21:20:51         Author:gogu

Json Formatter

I have this javascript code, that substracts from a total sum, a value when a checkbox is checked. In my case for each checkbox checked it substracts 20.

<script language="JavaScript">
    function Calculate(){
    var tag = window.document.getElementsByClassName("hsnb"), total = <? echo $total; ?>;
    for (var i in tag){
        total -= tag[i].checked && !isNaN(Number(20)) ? Number(20) : 0;
    }
    var cucu = + total.toFixed(2);

    if(cucu < "20"){  
        alert("You dont have enough points!");
        for(i = 1; document.getElementById("bifa" + i) !== null; i++) {
            if (document.getElementById("bifa" + i).checked){

            } else {
                document.getElementById("bifa" + i).disabled = true;
            }
        }
    }

    window.document.getElementById("outputDiv").innerHTML = '<span style="font-size:20px;">You have: POINTS' + cucu + '</span>';
}​
</script>

I want to give each checkbox a certain value, let's say:

<input type="checkbox" id="check" name="check" value="10">
<input type="checkbox" id="check" name="check" value="20">

And if i check the first checkbox it should substract 10 and if i check the second checkbox substract 20. You know what i mean, substract the value for each checkbox. Can you help me with this?

Author:gogu,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/13529991/javascript-checkbox-values
wezzy :

Hi you should try using jQuery, something like\n\nvar sub = 0;\njQuery(\"input[name=check]:checked\").each(function(index, element){\n sub = sub + jQuery(element).val();\n});\nvar total = yourNumber - sub;\n\n\nI'haven't tested this snippet but it should work\n\nHope it helps",
2012-11-23T13:24:38
yy