简体   繁体   中英

getting numbers from multiple text boxes (loop) and writing an equation

I am wondering why this loop works even when I add extra variables because I am curious. I only expected numbers1 to work in the loop. Sorry I am new to Javascript

It works regardless of how many fields you add because you're using getElementsByName to get the fields with name="s" and name="a" , which will find all of the fields with those names regardless of how many there are, and you're using a loop.

Note, though, that your output will always only be last pair of results because you're assigning to the #sum element's innerHTML .

I don't understand what you don't understand. The program sums the values in the elements named "s" and "a".

It uses one loop to sum them together at the same time, which is a bad idea: it only works if there are equal number of elements.

Separate the two:

function sumElementsByName(name) {
    var texts = document.getElementsByName(name);
    var sum = 0;
    for (var i = 0; i < texts.length; i++) {
        sum += parseInt(texts[i].value || 0);       
    }
    return sum;
}

document.getElementById("btn").addEventListener("click", function() {
    var sum_s = sumElementsByName("s");
    var sum_a = sumElementsByName("a");
    document.getElementById("sum").innerHTML = sum_s + " and " + sum_a;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM