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).
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);
});
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.