user3343502
user3343502

Reputation: 15

getElementsByName with multiple input names

i'm making some auto sum input calculator for me, but i have problem, because i don't know how to select multiple inputs which have different names. I know i could just use 'input' instead of exact name, but i need to do calculations just for 5-6inputs not all, so please help me to do it this way..

Code looks now like this:

<script type="text/javascript">
function findTotal(){
    var arr = document.getElementsByName('test1');
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
    }
    document.getElementById('total').value = tot;
}
</script>

So i would like to calculate exactly test1, test2, test3, test4, test5 inputs.

Thanks

Upvotes: 1

Views: 6757

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123433

You can use multiple attribute selectors with querySelectorAll():

var arr = document.querySelectorAll('[name="test1"], [name="test2"], [name="test3"], [name="test4"], [name="test5"]');

Though, if they share a common class name, you can select them by that:

<input name="test1" class="totaled">
<input name="test2" class="totaled">
<!-- etc. -->
var arr = document.querySelectorAll('.totaled');

Or, if they share a common parent element, you can find them from it:

<div id="the-parent">
    <input name="test1">
    <input name="test2">
    <!-- etc. -->
</div>
var arr = document.querySelectorAll('#the-parent input');

// or
var arr = document.getElementById('the-parent').getElementsByTagName('input');

Upvotes: 9

Related Questions