Skip to content
Advertisement

Access Google Tag Manager dataLayer field values on gtm.formsubmit

I am trying to pick up the selected value for a drop down field on a form when the form is submitted. Through the developer console in Chrome, I can see the value I want in the GTM dataLayer. It is inside the gtm.element[1] in the screenshot.

enter image description here

However, when I access that with dataLayer[5]["gtm.element"] the console returns the HTML for the form itself without the JSON structure or rest of the data I need to access.

enter image description here

Is there a way to access gtm.element and keep the JSON structure in the first screenshot?

Advertisement

Answer

Is there a way to access gtm.element and keep the JSON structure in the first screenshot?

Yes, when directly displaying a DOM element, the console prefers to render its HTML/XML view, but within JS you are working with an Object for this DOM Element, here a HTMLFormElement.

For example, in the chrome console using dir and dirxml, you can examine each element as JSON or XML respectively:

 > f=document.querySelector("form");
 // or f = dataLayer[5]["gtm.element"]
 > typeof f
 > console.dir(f)
 > console.dirxml(f)
 > console.dir(f[1])
 > console.dir(f.elements[1])
 

(The HTMLFormElement[#] syntax is a shortcut for HTMLFormElement.elements[#] since the form itself is not directly an array-like collection.)

Therefore dataLayer[5]["gtm.element"][1] is the desired select element, and a simple GTM JS variable to get its value may look like:

// MyformSubject requires the corresponding auto event variable
function(){
   return {{Form Element}}[1].value
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement