0

I want to count my values with a for loop. Probably it is easy but it would really help me! The value of rokenval, roken2val...... is in my html with an option value

Javscript..

function optellen(button, number){

button.addEventListener("click", function(){

    var rokenVal = document.getElementById('roken').value;
    var roken2Val = document.getElementById('roken2').value;
    var bewegenVal = document.getElementById('bewegen').value;
    var bewegen2Val = document.getElementById('bewegen2').value;

    var stressVal = document.getElementById('stress').value;
    var stress2Val = document.getElementById('stress2').value;
    var ongezondVal = document.getElementById('ongezond').value;
    var ongezond2Val = document.getElementById('ongezond2').value;

    var total = Number(rokenVal) +
                Number(roken2Val) +
                Number(bewegenVal) +
                Number(bewegen2Val) +
                Number(stressVal) +
                Number(stress2Val) +
                Number(ongezondVal) +
                Number(ongezond2Val);


    document.getElementById("resultaatveld").innerHTML = "Overlevingspercentage: " + total + "%";

}; optellen(btntest, 50);

1
  • If you want help, you're better off simplifying your example so that you're just focusing on what isn't working as expected. Nobody wants to tackle a huge wall of code that's mostly irrelevant to your problem. Commented Apr 6, 2015 at 17:18

1 Answer 1

1

One clever way to tackle your problem could be with the document.querySelectorAll method. Try this:

var inputs = document.querySelectorAll( '#form-id input' )
var total  = 0

for( var i = 0; i < inputs.length; ++i )
{
    total += ( inputs[ i ].value * 1 ) || 0
}

The "total" variable will now contain the sum of any numerical values within your inputs. You could modify this slightly to also work for select inputs as well.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.