Reputation: 1096
I'm very new to javascript and i'm trying to loop through a variable to increment the id to 60. I have a form that users input numbers into then I need it to add them up. This is what I have so far.
<input type="text" onkeyup="addNumbers()" id="name1">
<input type="text" onkeyup="addNumbers()" id="name2">
<input type="text" onkeyup="addNumbers()" id="name3">
etc..
<input type="text" id="total" disabled>
function addNumbers(){
var name = []
for( var i = 0; i < 60; i++ ) {
name[i] = parseInt( document.getElementById("name" + i).value );
}
var total = document.getElementById('total').value = var;
}
</script>
I'm not getting any output from the above code, so i'm not sure what i am doing wrong here.
Upvotes: 0
Views: 6891
Reputation: 14589
Try this. You have to iterate from index 1 to 60 and find the values of each input box. If value is valid, find sum and assign to total. JSFiddle
addNumbers = function(el){
var total = 0;
for( var i = 1; i <= 60; i++ ) {
var val = parseInt(document.getElementById("name" + i).value);
if(val>0){
total += val;
}
}
document.getElementById('total').value = total;
}
Upvotes: 1
Reputation: 29
Yeah.. got it.. you should pass the value from input text box on dom elements like..onclick="return functionname(this.value)"
and use rest as it is in the javascript function as TGH answered.
Upvotes: 0
Reputation: 39278
var total = 0;
for( var i = 0; i < 60; i++ ) {
total += parseInt( document.getElementById("name" + i).value );
}
document.getElementById('total').value = total;
Try this. Your current code is close, but you are using an array which complicates things. Also you are assigning var
to the element which is invalid.
Upvotes: 0
Reputation: 1366
the best way is to add a class. then get elements by class name. that will give you a array of input elements. then you can easily iterate through the list to get value of input item and add them together. Its best to do this way so you dont have hardcode the number of inputs :)
Upvotes: 0