Question Locked

Error retrieving input value in window onload function

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

My html code displays a table, which includes an input (fname) which After the table, I have this script:

window.onload = function ()
varSepType =document.getElementById('fname').value
window.alert(varSepType );
ChangeSName(varSepType );

The purpose of the script is to call a function, which changes the colour of one table element. I don’t want to set the colour in the table, because the function is also called by an onChange and I want the code to not be duplicated.
However, the console says “Uncaught TypeError: document.getElementById(...) is null”, despite the input having am initial value (it is set to a session variable & I can see on screen that it has been set).
I’m using WordPress.
Any ideas, please?

3 replies

by kees_b edited

"is null" means that it doesn't exist. And things that don't exist don't have a value.
You see something else than you're asking for. Are you using the right quotes?

Just call the onChange routine after the form is loaded.

by benstock2244

The error "Uncaught TypeError: document.getElementById(…) is null" indicates that the script is trying to retrieve an element with the specified ID ('fname'), but it is not finding any such element in the HTML.

Possible solutions:

Ensure that the input element with the ID 'fname' is present in your HTML code.

Check if the script is placed after the HTML content, allowing the DOM to fully load before trying to access the element.

Ensure that there are no typos in the ID ('fname') and that it matches the actual ID of the input element.

By addressing these issues, you should be able to resolve the "Uncaught TypeError" and successfully retrieve the input value in your window.onload function.

by cassharper030 edited

The error appears because the script tries to access the input element (document.getElementById('fname')) before the table (and hence the input) has fully loaded in the browser. Here's why you're getting the error and how to fix it:

The Issue: window.onload runs after the entire page loads, but in your case, the table with the input might be loading asynchronously or after the script runs.

The Fix:

Move Script Placement: Try placing your script containing the window.onload function right before the closing </body> tag. This ensures the script runs after all the HTML elements have loaded.

Use DOMContentLoaded Event: Instead of window.onload, use document.addEventListener('DOMContentLoaded', function() { ... }). This event triggers when the HTML structure is ready, including your table and input element.

This should allow your script to access the fname input value without the "null" error.

This discussion is closed to new replies.