New to javascript! This works, but I have a lot more to do, and it would be great if there was a cleaner way to do this.. open to using jquery if neccesary :)
(stack
var answer = 0;
for(var i = 1; i <= 20; i++) {
answer += parseInt(document.getElementById("backer-prediction-" + i).value), 10);
}
document.getElementById("backer-prediction-answer").value = answer;
The cleanest way to go about this would be to give each of the backer-prediction-#
elements a class and grab all of them:
var backerEls = document.querySelectorAll('.backer-prediction');
//Get a list of all the elements with the class 'backer-prediction'
var backers = 0;
//Total
for (var i = 0; i < backerEls.length; i++) {
//Loop over the elements
backers += parseInt(backerEls[i].value, 10);
//Parse their values and add them to the total
}
console.log(backers);
(Demo)
This lets you have as many elements as you want without having to update your JS at all.
You can use the following code to get the backers total.
function apply(){
var answer = getBackers();
document.getElementById("backer-prediction-answer").value = answer;
}
function getBackers()
{
var baseName = "backer-prediction-";
var elementId = "";
var backers = 0;
for(var i = 1; i < 20; i++)
{
elementId = baseName + i;
backers = backers + getElementValue(elementId);
}
return backers;
}
function getElementValue(elementId)
{
var value = document.getElementById("backer-prediction-1").value;
return parseInt(value, 10);
}
I'd do it something like this:
function apply() {
var backers = 0;
for (var i = 1; i < 20; ++i) {
backers +=
parseInt(document.getElementById("backer-prediction-" + i).value);
}
document.getElementById("backer-prediction-answer").value = backers;
}