Error message keep showing up with "TypeError: document.getElementById(...) is null"

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 (&#8364;): <input id="budgettarget" type="text" class="boxmed"/>
                    Remaining (&#8364;): <input id="remaining" type="text" class="boxmed" readonly/>
                </th>
            </tr>
           <!-- Continue with table rows and cells -->
        </table>
    </fieldset>
    </form>
</body>

Answer №1

It appears there is a discrepancy in your loops as they begin with i = 0, but your HTML elements start with 1, such as r1. There could be other errors present (like the issue mentioned with = instead of using ===), but since the code is incomplete, it makes it difficult to pinpoint all of them.

Answer №2

It appears that there may be an issue with the following code snippet:

if (Accounts[i]=null)
                    Accounts[i]='Account #'+i;

To properly check whether Accounts[i] is equal to null, you should use == (or possibly === in javascript). Currently, you are setting null as the value of Accounts[i].

Answer №3

It appears that the incorrect operator "=" was used for comparison instead of "== or ===, which are the correct operators to use. Using "=" assigns a value, such as null, to account[i].

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing a node module in a web browser

I'm attempting to upload and read an Excel file with the help of a node module called read-excel-file. Following the instructions for usage in the browser, I have added the following code snippet to my .js file: import readXlsxFile from 'read-ex ...

Am I using async/await correctly in this code?

Here is the code snippet I am currently working with: var process = async (items: DCXComposite[], session: Session) => { // This function returns a response object with a statusCode property. If the status Code is 200, it indicates a ...

Choosing an element with JavaScript

var displayedImage = document.querySelector('.displayed-img'); var thumbBar = document.querySelector('.thumb-bar'); btn = document.querySelector('button'); var overlay = document.querySelector('.overlay'); /* Itera ...

How to use Javascript to pause an HTML5 video when closed

I am new to coding and currently working on a project in Adobe Edge Animate. I have managed to create a return button that allows users to close out of a video and go back to the main menu. However, I am facing an issue where the video audio continues to p ...

Associate the callback function with a directive that does not have an isolated scope

Ensuring the correct context when binding a callback function to a directive is crucial. When working with an isolated scope, this task is easily accomplished. <bar-foo callback="mycontroller.callback()"></bar-foo> The directive code: ... ...

JavaScript is always overlooked and goes unused

Can you figure out why the Javascript code isn't working? <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <script type="text/javascript"> function ChangeDisplay() { alert("Changing"); document ...

sophisticated authorization structure for sails.js and angular

Thinking about developing some applications using sails.js and angular.js I'm in search of a way to create adaptable permissions. I want the ability to control permissions for model operations (CRUD) and functions within models. Additionally, it shou ...

Display Error with Custom Alert Box

I recently implemented a customized alert box from slayeroffice's website, which you can find at slayeroffice.com/code/custom_alert/. When I view it on my browser, the alert box appears with a blue color in the center of the screen. Here is how it lo ...

How can I use JavaScript to disable a table row and then save the selected option in a MySQL database?

I have a PHP snippet that dynamically displays table rows. Each row contains a radio button with "Yes" and "No" options. I have implemented a JS function where, upon choosing an option, a pop-up box is displayed. If the user selects the "Yes" option in t ...

How does Ruby on Rails facilitate interactions between multiplayer users and visitors?

I am looking to create a way for visitors to interact on my website. Imagine a virtual chat space. This involves collecting and sharing data among users, which can be accomplished using ajax or similar methods. However, I'm wondering if there are ex ...

Should I generate an array or pull data directly from the database?

Hey there, I've got this JavaScript app and could really use some input or tips. Here's the idea: Users log in to try and defeat a 'boss', with each player working together in the game. Let's say the 'boss' has 10 millio ...

I'm struggling to solve a straightforward jQuery sliding issue

I am struggling to make text slide from right to left on my website. I want the text to appear only when the page loads or refreshes, and then slide off when a link is clicked, revealing new text. Can anyone help me figure this out? http://jsfiddle.net/XA ...

The function called Nuxt: n2 is not defined

When using Nuxt 3, I encountered a TypeError that looks like the following: Uncaught TypeError: n2 is not a function My issue revolves around a button that triggers the function toggleSelectRow with a @click.prevent directive. The function in question is ...

The visibility in the viewport is always showing as visible for all elements upon loading

Seeking advice from fellow developers! I'm encountering an issue with my code meant to detect when items are in the viewport. Strangely, the first .each loop is returning 'visible' for every item, even though it's not triggered by scrol ...

Having trouble accessing the offsetHeight property from a React Ref

I've been attempting to retrieve the size of a div element inside the React render method, but I always seem to get offsetHeight, offsetWidth as 0. Interestingly, the actual values of offsetHeight, offsetWidth are visible when using console.log. Is ...

What is the proper way to implement an if-else statement within objects?

Is there a way to convert the code below into an object structure so I can access nodID and xID keys from different files? The issue lies in the if statement within the code. My idea is to use export const testConfig = {} and import testConfig into any fil ...

How do we insert an element into an array with a fixed memory size?

Recently, I reached the Algorithm section of JavaScript and learned that an array cannot grow. However, I am confused about how we can push items into an array. Is the "array" copied and new memory added for additional items? ...

Is it possible to submit two forms simultaneously using jQuery or AJAX?

My plan is to save 2 forms, with the first form providing the Foreign key for the second form. This is my attempt at saving this using JavaScript: $("#btnSave").click(function (e) { e.preventDefault(); $('#workForm').submit(); ...

Performing Batch Writes in Firestore using the Admin SDK

I have a massive ASCII flat file containing 1.5 million lines, which is essentially a list of parts from a manufacturer. I want to store this data in Firestore. Originally saved as a .csv file, the size was 250GB. After converting it to a JSON file using ...

AngularJS is encountering an issue with the callback function, resulting in an error

Currently, I am utilizing the $timeout service in Angular to decrease a variable from 100 to 1 in increments of 1/10 seconds. Although I understand that using the $interval service would be a simpler solution, for this particular scenario, I am focused on ...