1

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

user3343502
  • 15
  • 1
  • 4

1 Answers1

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 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');
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • Ty buddy, i did it with querySelectorALL :) Thans – user3343502 Feb 23 '14 at 21:20
  • One more question, would be hard to change my script to show numbers with decimals ( as money? ) – user3343502 Feb 23 '14 at 21:56
  • @user3343502 There's actually another question just for that: [How can I format numbers as money in JavaScript?](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) – Jonathan Lonowski Feb 23 '14 at 22:09
  • Yeah,i found it, but problem is because i don't know how to implement it to my code :D – user3343502 Feb 23 '14 at 22:51
  • Alternatively: (and kinda unclean but easy to implement for any future readers) create a css class without any rules, and use getElementsByClassName for this. CSS class names are not limited, and as long as this one doesnt contain any rules it wont make any problems – Hobbamok Jun 18 '21 at 07:35