-3

Hey guys i have a question about calculating checkboxes and its total in real time so here is my code:

function calc() 

{
    theTotal = 0;
    checkForm = document.FormName;
    for (i=0; i <= checkForm.length-1; i++) {
        if (checkForm.elements[i].type == "checkbox") {
            if (checkForm.elements[i].checked == true) {
                document.getElementById("total").value = theTotal;
            }
        }
    }
    document.getElementById("total").innerHTML = theTotal;
}

Here is my html code:

<p>Total: $<span id="total">0</span></p>

    <tr>
    <td> <br> <center> <img src="Shirt1.jpg" width="160" height="150" alt="shirt1"> <br> <input type="checkbox" onchange="calc()" value="19.99"> <label for="rd1">Obey T-Shirt: $19.99</label> </center> </br></td>
    <td> <br> <center> <img src="Shoe1.jpg" width="160" height="150" alt="shoe1"> <br> <input type="checkbox" onchange="calc()" value="19.99"> <label for="rd1">Shoe - Red Lace: $19.99</label> </center> </br> </td>
    <td> <br> <center> <img src="Snapback1.jpg" width="160" height="150" alt="snap1"> <br> <input type="checkbox" onchange="calc()" value="19.99"> <label for="rd1">Snapback Bullets: $19.99</label> </center> </br> </td>
</tr>

When i click on one of the selected checkboxes it won't give me the calculation that i want. Are you able to help me with this one?

4

2 回答 2

1

您的代码中似乎有很多问题。在这里,我为您写得更简单。

您不需要遍历每个表单元素,即使您使用每个复选框单独调用它也是如此。

您还需要将其theTotal设为全局变量以获取已检查项目的总数。现在,您在每次函数调用时将其重置为 0。

你可以试试这个

var theTotal = parseFloat(0);

function calc(control) {
    if (control.checked == true) {
        theTotal += parseFloat(control.value);
    } else {
        theTotal -= parseFloat(control.value);
    }
    document.getElementById("total").innerHTML = theTotal;
}

并这样称呼它

<input type="checkbox" onchange="calc(this)" value="19.99">

JS 小提琴演示

于 2013-05-03T02:01:38.820 回答
1

您没有更新变量总计。

您应该阅读已检查输入的 .value

于 2013-05-03T01:46:58.097 回答