1

I currently have a series of checkboxes for different items, which when selected modifies a total. The JavaScript code is below.

<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 0.00;
for (i=0;i<document.listForm.choice.length;i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseFloat(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum.toFixed(2);
}

</script>

This code works fine, but all the checkboxes have the same input name 'choice'. I need to change this so each input name is different such as choice1, choice2, choice3 etc. How do I change the JavaScript to add up all the differently named checkboxes instead of just adding the ones that are called 'choice'.

Would appreciate any help, good HTML and CSS knowledge but very basic JavaScript. Thanks.

2 Answers 2

1

You could do something like:

function checkTotal() {
    document.listForm.total.value = '';
    var sum = 0.00;
    var i, inputs, input;

    inputs = document.getElementsByTagName('input')

    for (i=0;i<inputs.length;i++) {
        input = inputs[i]
        if (input.type === 'checkbox' && input.name.substr(0, 6) === 'choice') {
            sum = sum + parseFloat(input.value);
        }
    }
    document.listForm.total.value = sum.toFixed(2);
}

This isn't tested, but the code should look through the DOM for all input elements. Then it will iterate through them and check for the ones that are checkboxes that also have a name that begins with 'choice'. It will then add the checkbox's value to the sum.

Libraries like jQuery make this sort of stuff a lot easier.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for response, the total is not adding up with this code though. No idea why, it just remains at the initial value of 0.00.
any more ideas? would be very grateful!
I made a couple changes to the code. I think it will work now. If not, please post the HTML and any errors you get in the console. You can access the console in Chrome by following the directions at developers.google.com/chrome-developer-tools/docs/console
0

Using jQuery, the below code fragment will add all checkbox values on the page. I have not tested this, but it should work.

$("input[type=checkbox]").each(function(){
   if(this.checked){
     sum = sum+this.val();
   }
});

Comments

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.