Sometimes, we need to gather the information users enter into forms when tracking form submissions. Whether it’s for Enhanced Conversion tracking or creating Custom form submit events based on input values, collecting form data is crucial. However, picking and collecting values from form input fields can be challenging. To address this, I’ve created a simple yet powerful code that can collect data from any number of form fields—just four lines of code! In the tutorial ahead, I’ll provide a step-by-step guide on effortlessly gathering any form’s data and tracking form submissions.
Code For Form Data
//form data code
var contactForm = document.querySelector('#gform_2');
var formData = new FormData(contactForm);
var inputValues = {};
formData.forEach(function (value, key) {
inputValues[key] = value;
});
console.log(inputValues);
/**
* Author: Md Hasanuzzamna
* Linkedin: https://linkedin.com/in/md-h
* Youtube: https://youtube.com/@leomeasure
* Email: info@leomeasure.com
*/
GTM DataLayer Code for form Submit & Form Data
var contactForm = document.querySelector('#your-form-id');
if(contactForm) {
contactForm.addEventListener('submit', function () {
var formData = new FormData(contactForm);
var inputValues = {
event: 'contact_form_submit'
};
formData.forEach(function (value, key) {
inputValues[key] = value;
});
window.dataLayer = window.dataLayer || [];
dataLayer.push(inputValues);
});
}
/**
* Author: Md Hasanuzzamna
* Linkedin: https://linkedin.com/in/md-h
* Youtube: https://youtube.com/@leomeasure
* Email: info@leomeasure.com
*/