I have a program that I am currently trying to total.
The program is to have 10 numbers add into each text box and when the user hits the Sum button the program runs through the Add function and returns the total after the words 'Sum: '. The pages are linked with <script src="functions.js"></script> below the title tags.
Below are both pages.
function Add() {
var add_entries = 0;
for (i = 1; i <= 11; i++) {
var textentry = "Text" + i;
var x = Number(document.getElementById(textentry).value);
add_entries += x;
}
console.log(add_entries);
document.getElementById("Sum: ").innerHTML = add_entries;
}
Enter student test scores for all text boxes
<br>
<br>
<div>Blank responses will be treated as zeros.</div>
<br>
<br>
<div>Susan: <input id="Text1" type="text" /></div>
<div>Harry: <input id="Text2" type="text" /></div>
<div>Joe: <input id="Text3" type="text" /></div>
<div>Bill: <input id="Text4" type="text" /></div>
<div>Mary: <input id="Text5" type="text" /></div>
<div>Ken: <input id="Text6" type="text" /></div>
<div>Paul: <input id="Text7" type="text" /></div>
<div>John: <input id="Text8" type="text" /></div>
<div>Nora: <input id="Text9" type="text" /></div>
<div>Cindy: <input id="Text10" type="text" /></div>
<input id="Sum" type="button" value="Sum" onclick="Add()" />
<input id="Avg" type="button" value="Average" onclick="Avg()" />
<input id="High" type="button" value="Highest" onclick="Max()" />
<input id="Low" type="button" value="Lowest" onclick="Min()" />
<div>Sum: </div>
<div>Average: </div>
<div>Highest: </div>
<div>Lowest: </div>
for (i = 1; i <= 11; i++) 11 needs to be changed to 10 because you dont have Text11
document.getElementById("Sum: ").innerHTML = add_entries; ID is not correct
if you want the output set to your sum div you need to set an ID on it and put the id in document.getElementById(HERE)
EDIT Answer:
change this line
document.getElementById("Sum: ").innerHTML = add_entries;
to
document.getElementById("sumDiv").innerHTML = 'Sum: ' + add_entries;
and then add an ID to your div were you want the output to be
Like this <div id="sumDiv">Sum: </div>
document.getElementById("Sum: ").innerHTML = add_entries;
That's not a valid id. Give your div an id and use that.
<div id="mySum">Sum: </div>
document.getElementById("mySum").innerHTML = add_entries;
If you want to retain the "Sum:" you can use a span.
<div>Sum: <span id="mySum"></span></div>
document.getElementById("mySum").innerHTML = add_entries;
The for statement goes one step too far, if you check the console you will see an error stating something like, "TypeError: document.getElementById(...) is null", thats because its checking id="Text11" change:
for (i = 1; i <= 11; i++)
to:
for (i = 1; i <= 10; i++)
and maybe even check that document.getElementById(textentry) doesn't return null before using it. And of course, "use parseInt instead of Number" as Ameer said, or use a plus sign :/
+(document.getElementById(textentry).value);