Search code examples
javascriptmailchimpsquarespace

Adding a hidden form field to a dynamically generated Squarespace newsletter block using JS


I'm trying to add a hidden field to my homepage newsletter signup at http://greig.cc/ so that I can track the signup source in Mailchimp.

This is the code that I'm injecting into the page, but it throws an 'Uncaught TypeError: undefined is not a function' error and I can't work out why.

Is it something to do with the fact that the rest of the form is rendered after the page is loaded? (this is why I'm using the class name to target the form).

<script type="text/javascript">
var formcontainer = document.getElementsByClassName('newsletter-form');
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'SOURCE';
input.id = 'SOURCE';
input.value = 'homepage';
formcontainer.appendChild(input);
</script>

Thanks for reading :)


Solution

  • Fixed my doing two things :)

    (1) Waiting for the DOM to load before running the script
    (2) Iterating through getElementsByClassName to get the first item in the array. {Not bothering to loop through this as I only have 1 form per page}

    <script language="JavaScript">
    document.addEventListener("DOMContentLoaded", theDomHasLoaded, false); 
    function theDomHasLoaded(e) {
      var formelements = document.getElementsByClassName('newsletter-form');
      formelements[0].innerHTML += "<input name='SOURCE' id='SOURCE' type='hidden' value='homepage' />";
    }
    </script>