Reputation: 3025
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.
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.
Is there a way to access gtm.element
and keep the JSON structure in the first screenshot?
Upvotes: 2
Views: 805
Reputation: 13495
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
}
Upvotes: 3
Reputation: 383
I believe what you are trying to accomplish is not possible. This representation you see on the first screenshot is not a GTM exclusive thing. If you add a form inside any array in Javascript you will get that format. It's not that the element was converted to an array, it's only being shown that way on the console.
It should still be possible to access the element using the code you provided though, since the HTML element will still be treated as an array, but I believe this is not what you're trying to achieve. (I'm guessing here that the selected element will not always be the second one in the array)
That said, it should be possible for you to access the value you want through the element itself. I can't say for sure what structure you'd need to use since I don't have the HTML available, but you can probably use a querySelector to get the element you want.
You can use the "Form Element" GTM variable to access the form through a Custom HTML tag and then query the selected value through it.
Upvotes: 2