Error retrieving form input value in window onload function

My html code displays a table, which includes an input (fname).

After the table, I have this script:

<script>
window.onload = function () {
	varSepType =document.getElementById('fname').value
	window.alert(varSepType);
	
	ChangeSName(varSepType);
	}
</script>

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 code, 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?

The error suggests that the script is executing before the element with the ID “fname” is available in the DOM.

A couple of things to check:

  • Ensure that the ID “fname” matches the ID of your input element in the HTML. IDs are case-sensitive.
  • Since you’re using WordPress, it’s possible that the input field is being loaded dynamically (perhaps by a plugin or widget) after the initial page load, so it might not be immediately available when your script runs.

To address this, try moving the script to the bottom of the <body>, which ensures that all DOM elements are loaded before the script executes.

Also, try using DOMContentLoaded instead of window.onload. The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed.

document.addEventListener('DOMContentLoaded', function () {
    var varSepType = document.getElementById('fname').value;
    window.alert(varSepType);
    
    ChangeSName(varSepType);
});

LMK if that makes any kind of difference.

1 Like

Thank you James. I added your addEventListener lines and the window.alert didn’t happen. I then tried putting the lines into a plugin which adds them to the footer, same non-result. So I will try to build the logic into the HTML table.

No problem. Do you have a link to a page where we can see this happening?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.