So i am trying to make a js to run when the page loads initially but am failing to trigger it. 
not sure where i am failing
my js looks like this
<script type="text/javascript">
AJS.toInit(function() {
console.log("Script loaded and running in AJS context!");
var nameFieldName = "ProductGroup";
var emailFieldName = "recipientEmail";
var emailMap = {
"john": "john.dow@gmail.com",
"team": "team.all@gmail.com",
"mary": "mary.pop@gmail.com"
};
var nameField = document.querySelector('[name="' + nameFieldName + '"]');
var emailField = document.querySelector('[name="' + emailFieldName + '"]');
console.log("Dropdown field:", nameField);
console.log("Email field:", emailField);
if (nameField && emailField) {
function updateEmail() {
var selectedID = nameField.value;
var email = emailMap[selectedID] || "";
console.log("Selected:", selectedID, "Setting email:", email);
emailField.value = email;
}
nameField.addEventListener('change', updateEmail);
updateEmail();
} else {
console.log("Fields not found. Double-check field names.");
}
});
</script>
ps. it runs fine if i try to manually run it via console