0

Hello everyone. I am new here but have lurked quite a lot.

I have multiple forms that contain drop downs that need to be summed together. My current JS passes through a couple check box values then calculates. All of this works swimmingly. The place I have been getting stuck is I want to use this JS across all my forms regardless of the number of dropdowns. My current code is:

<script type="text/javascript">
function updatesum() {
if (document.getElementById("autofail1").checked == true) {
document.form.totalscore.value = "0";
}
else if
(document.getElementById("autofail2").checked == true) {
document.form.totalscore.value = "0";
}
else
{
document.form.totalscore.value =
(document.form.category1.options[document.form.category1.selectedIndex].text-0) +
(document.form.category2.options[document.form.category2.selectedIndex].text-0) +
(document.form.category3.options[document.form.category3.selectedIndex].text-0) +
(document.form.category4.options[document.form.category4.selectedIndex].text-0) +
(document.form.category5.options[document.form.category5.selectedIndex].text-0) +
(document.form.category6.options[document.form.category6.selectedIndex].text-0) +
(document.form.category7.options[document.form.category7.selectedIndex].text-0) +
(document.form.category8.options[document.form.category8.selectedIndex].text-0) +
(document.form.category9.options[document.form.category9.selectedIndex].text-0) +
(document.form.category10.options[document.form.category10.selectedIndex].text-0) +
(document.form.category11.options[document.form.category11.selectedIndex].text-0) +
(document.form.category12.options[document.form.category12.selectedIndex].text-0) +
(document.form.category13.options[document.form.category13.selectedIndex].text-0) +
(document.form.category14.options[document.form.category14.selectedIndex].text-0) ;
}
}
</script>

Thank you for your help.

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by AleMonteiro
0

This will sum all values from all selects in the document that begins with 'category':

window.onload = function() {
            var sum = sumSelects('category');
            alert('Sum of Category: ' + sum);
        }

        function sumSelects(name) {
            var selects = document.getElementsByTagName('select'),
                sum = 0;
            for(var i=0, il=selects.length; i<il; i++) {
                var
                    slc = selects[i],
                    slcName = slc.name;

                if ( slcName.indexOf(name) > -1 ) {
                    sum += getValue(slc);
                }
            }   
            return sum;
        };

        function getValue(slc) {
            return parseInt(slc.options[slc.selectedIndex].text);
        };
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.