I'm trying to collect and fire form fields as dataLayer variables using Google Tag Manager:
<script>
var fields = [];
var fields = document.querySelectorAll("input");
var x = fields.forEach(function(field) {
var obj = {};
var a = field.getAttribute("name");
var b = field.value;
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
obj[a] = b
});
});
</script>
My intention is, when triggered, to:
However, I'm receiving the error:
Error at line 12, character 10: Parse error. '}' expected
And no matter what changes I make, I can't seem to properly trouble shoot.
You can't have a =
in the push
function. You can change your code slightly.
Do the assignment before pushing like obj[a] = b
, and then push the object in dataLayer at each iteration.
Working code logic below
var fields = [];
var fields = document.querySelectorAll("input");
var x = fields.forEach(function(field) {
var obj = {};
var a = field.getAttribute("name");
var b = field.value;
obj[a] = b;
window.dataLayer = window.dataLayer || [];
window.dataLayer.push(obj);
});
console.log(dataLayer)
<input name='a' value='a' />
<input name='b' value='b' />
<input name='c' value='c' />