...

View Full Version : How to get the total as a variable?



Drew012
07-06-2012, 03:25 AM
I have a list of questions. For each of them the user inputs a number from 0 - 100. The sum of the three numbers needs to be assigned as a variable. I am going to use that variable in a basic HTML chart where a plugin can change it.

So my question is from this code:



else if (countId == "Q5" || countId == "Q13" || countId == "Q21") {
var nFinancial = 0.0;
nFinancial = parseInt(document.getElementById("Q5").value);
nFinancial += parseInt(document.getElementById("Q13").value);
nFinancial += parseInt(document.getElementById("Q21").value);
tallyTable.rows[0].cells[4].firstChild.data = nFinancial;
}



As you can see for this block which is contained in a bigger funtion contains three question (Q5, Q13, and Q21). It functions properly but I need the result as a variable. This is not my code and I thought that nFinancial was the var that represented Q5+Q13+21. However, when I try to alert() the nFinancial var it does nothing when it should default at 0.0.

Thanks for your time, I can post more of the code if needed but this section was the one giving me the problems.

Old Pedant
07-06-2012, 03:34 AM
nFinancial *is* the variable.

But WHERE are you trying to do alert(nFinancial)?

If the code you show there is inside some function and your alert( ) is NOT inside that same function then it will indeed have no value.

Drew012
07-06-2012, 05:06 AM
nFinancial *is* the variable.

But WHERE are you trying to do alert(nFinancial)?

If the code you show there is inside some function and your alert( ) is NOT inside that same function then it will indeed have no value.

Thanks, I sort of figured out what I was doing based on this. Turns out I was expecting an alert() message to pop up as I loaded the page but since it was in an if statement I had to execute that if statement first.

However, now lets say I want to call the var 'nFinancial' again. I know it works inside of this function where it was named, but is there a way to re-use the function lets say at the end of the page?
So basically...



<body>
<script>
// my entire function goes here, and here is the only place I can use the variables created in the function
</script>
//I want

Philip M
07-06-2012, 07:28 AM
Declare the variable outside a function to make it global scope, available to any function in the script.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum