admin管理员组

文章数量:1310455

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

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

Share Improve this question asked Feb 23, 2014 at 20:45 user3343502user3343502 151 silver badge4 bronze badges 2
  • 1 document.getElementsByTagName is your friend – Mabedan Commented Feb 23, 2014 at 20:46
  • I think document.getElementsByTagName is not solution, because i have in script 100inputs, but need to calculate only exactly 5 inputs, not all. – user3343502 Commented Feb 23, 2014 at 20:50
Add a ment  | 

1 Answer 1

Reset to default 9

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 mon 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 mon 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');

本文标签: javascriptgetElementsByName with multiple input namesStack Overflow