Passing the value of a form field into Google Tag Manager is pretty straight forward with the dataLayer and the dataLayer variable. But since things vary a bit case to case, I’d like to show one example which you can adapt.
The basics are:
- If you have any formSubmit trigger present in your container, then on submit of any form, a gtm.form object will be passed into the dataLayer.
- This object contains all the information, especially hidden fields and whatever the visitor filled out.
- Those values in turn can be retrieved in GTM using a dataLayer variable.
Alright, for sake of this exercise, I’ll try to get a hidden field, which contains meta information about the form. This is a common practice in IT agencies.
My HTML code looks something like this. This is simply the WP comment form, but it will do the trick. (1) is the textarea, which we can retrieve the value of, and (2) is a hidden input with meta information.
Digging Into The dataLayer Object
Ok, I’ve submitted a test comment, and now I want to figure out where I can find my hidden value.
To figure out where the dataLayer element you are looking for is hidden, you can use the Web Dev Tools in Chrome; the Console view.
If you submitted a form, but cannot see a gtm.formSubmit element in your dataLayer it’s because you don’t have a formSubmit trigger present on the page. Next you navigate to whatever you need. The standard place to find form values is here:
You can first click in the Console and then test by entering your element in bracket notation. To retrieve the textarea, you can enter:
Sometimes, you will not be able to find the hidden field you are looking for, in that case you’ll have to dig into the node elements
Turning This Into Dot Notation
Alright, once you have the element you want to retrieve, you turn the bracket notation from above into the “dot notation” used by Google Tag Manager.