-1

I have an ajax code which is concepted from auto calculate the sum of input values with javascript. So I'd like to add more field to meet my needs. Then I added some inputs[checkbox] with given value in it. The idea is when the box is checked. Its value will be calculated to the process just like type in the input[text].

Here's the code :

<script language="javascript">
function AddInputs()
{
    var total = 0;
    var coll = document.getElementsByTagName("input")
    for ( var i = 0; i<coll.length; i++)
    {
        var ele = coll[i];
        total += parseInt(ele.value);
    }
    var Display = document.getElementById("Display");
    Display.innerHTML = total;
}
</script>

Here's the form:

<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<input onkeyup="AddInputs()" />
<input type="checkbox" onkeyup="AddInputs()" value="100" />
<span id="Display"></span>

The problem is I can't make the checkbox to get calculated with those input boxes. Please suggest.

1 Answer 1

0

That's because onkeyup event is fired when you release a key on the keyboard and this doesn't happen when you click the checkbox. You should use either onchange (but this won't work in older IEs) or onclick.

Also note that the value of 100 will always be added to total. If you want to count the checkbox only if it's checked, use something like

if (ele.type !== 'checkbox' || ele.checked) {
    total += parseInt(ele.value);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your method doesn't works: code <script language="javascript"> function AddInputs() { var total = 0; var coll = document.getElementsByTagName("input") for ( var i = 0; i<coll.length; i++) { if (ele.type !== 'checkbox' || ele.checked) { total += parseInt(ele.value); } } var Display = document.getElementById("Display"); Display.innerHTML = total; } </script> <input onkeyup="AddInputs()" /> <input onkeyup="AddInputs()" /> <input onkeyup="AddInputs()" /> <input type="checkbox" onkeyup="AddInputs()" value="100" />+100 <span id="Display"></span>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.