views:

147

answers:

3

I'm new to javascript and a novice programmer, so this might be a really easy question to answer. I would like to loop over the values of x number of fields and add them up to display the sum in a final field. I can perform this function if I explicitly call each field, but I want to abstract this so I can deal with a flexible number of fields. Here's example code I've come up with (that's not working for me). Where am I going wrong?

<html>
<head>
<script type="text/javascript">
function startAdd(){
    interval = setInterval("addfields()",1);
}
function addfields(){
    a = document.addition.total.value;
    b = getElementByTagName("sum").value;
    for (i=0; i<=b.length; i++){
        a+=i;
    }
    return a;
}
function stopAdd(){
    clearInterval(interval);
}
</script>
</head>

<body>

<form name="addition">

 <input type="text" name="sum" onFocus="startAdd();" onBlur="stopAdd;">
+ <input type="text" name="sum" onFocus="startAdd();" onBlur="stopAdd;">
= <input type="text" name ="total">

</form>

</body>
</html>
A: 

There are no tags in your code named 'sum'. I'd suggest using a class attribute on your input tags and then using getElementsByTagName('input') and checking they have the relevant class. jQuery would simplify this enormously, because you would be able to select all elements with a certain class in a single line: $(".className"). If you don't want jQuery, this question might be of interest.

spender
A: 

I would use the jQuery Library and do a pattern match to get all the elements you want to add and then put that in your output field

Avitus
+1  A: 

There are two things wrong with your code.

The first one:

b = getElementByTagName("sum").value;

You probably mean to getElementsByTagName (notice the extra s). Also, there are no <sum> elements, which is a problem, because you'll get no results. Finally, .value would return the value property of the array (and because none exists, you'll get back undefined), and not an array of the value properties of each element.

To solve these problems, you can write it like this:

inputElements = getElementsByTagName('input');
sumValues = [ ];

for(i = 0; i < inputElements.length; ++i) {
    if(inputElements[i].name == 'sum') {
        sumValues.push(inputElements[i].value);
    }
}

Or in jQuery:

sumValues = $('input[name=sum]').map(function() {
    return this.value;
});

The second one:

for (i=0; i<=b.length; i++){

b.length describes the number of elements. With <=, you are then accessing b[b.length], which doesn't exist. You want to access up to b[b.length - 1], so the most idiomatic way to write this is to rewrite the condition to use < instead of <=. That is:

for(i = 0; i < b.length; ++i) {
strager