While trying to solve the exercise on creating a budget calculator, I encountered some errors in my code that were not present in the professor's solution. Even though I filled out all the necessary tables, I kept getting errors when attempting to update my form elements using DOM manipulation:
In Google Chrome, the error was: Uncaught TypeError: Cannot read property 'style' of null And in Firefox, the error was: TypeError: document.getElementById(...) is null
Upon loading the page, the body calls the function formInit().
var Accounts = new Array("blah", "blah1");
var MoneySpent = new Array();
var Rates = new Array();
var bud = 1000;
var rem;
var maxrate = 100;
var i;
function initArrays(){
for (i=0; i < 20; i++){
if (Accounts[i] == null)
Accounts[i] = 'Account #' + i;
MoneySpent[i] = 0;
Rates[i] = 0;
rem = 1000;
}
}
function updateFormElements(){
for (i=0; i < 20; i++){
document.getElementById("r" + i).style.background = '#bbb';
document.getElementById("a" + i).value = Accounts[i];
document.getElementById("m" + i).value = MoneySpent[i];
document.getElementById("r" + i).value = Rates[i];
}
document.getElementById("budgettarget").value = budget;
document.getElementById("remaining").value = rem;
if(rem < 0)
document.getElementById("remaining").style.background = 'red';
}
function formInit(){
initArrays();
updateFormElements();
}
The JavaScript file containing more functions is included in the script section of the head tag. Moving past this stage will allow me to check the remaining parts of the code. The HTML structure is as follows:
<body onload="formInit();"><br />
<form id="budForm" action="">
<fieldset>
<legend> Budget Calculator </legend>
<table >
<tr>
<th colspan="6"> Red indicators over budget | Grey indicators read only zone! </th>
</tr>
<tr>
<th colspan="6"> Budget Target (€): <input id="budgettarget" type="text" class="boxmed"/>
Remaining (€): <input id="remaining" type="text" class="boxmed" readonly/>
</th>
</tr>
<!-- Continue with table rows and cells -->
</table>
</fieldset>
</form>
</body>