If you have a task to track the efficiency/correctness of filling out a form consisting of several fields, this script will help you. It allows you to record in what sequence the user interacted with the form fields before leaving the page.
Here is the script code, it must be published using Google Tag Manager on the page with the form you are interested in:
<script>
(function() {
var formSelector = 'form'; // Form selector
var history = [];
var i;
var checkSubmit = function() {
i = window.dataLayer.length - 1;
while (i > -1) {
if (window.dataLayer[i]['event'] === 'gtm.formSubmit') {
return true;
}
i--;
}
};
window.addEventListener('beforeunload', function() {
if (history.length && !checkSubmit()) {
var label = history.join(' > ');
window.dataLayer.push({
'event': 'UAevent',
'eventCategory': 'Behaviour',
'eventAction': 'Form Actions',
'eventLabel': label
});
}
});
document.querySelector(formSelector).addEventListener('change', function(e) {
var stage = e['target'].getAttribute('name').replace('RegistrationForm', '');
if (history.length == +0) {
history.push(stage);
}
if ((history[history.length - +1] != stage) && (history.length > +0)) {
history.push(stage);
}
});
})();
</script>
In the example, we have a form where elements have a name
attribute, like name="RegistrationForm[email]"
. And we keep track of when the user changes these elements, that is, he enters something, pokes selects, etc.
Next, the script waits for the beforeunload
event, that is, the visitor leaves the page, and resets the history of interactions with fields in GA.
In the event report, we will see something like this:
Event Label | Total Events |
---|---|
[confirm] | 34448 |
[email] > [name] > [confirm] | 9342 |
[email] > [name] | 3945 |
[name] > [confirm] | 2559 |
[confirm] > [name] | 1491 |
[email] | 1469 |
[name] | 1298 |
[name] > [email] | 680 |
[email] > [name] > [email] | 569 |
[confirm] > [email] > [name] | 303 |
This should already be enough for you to form some hypotheses about the existence in the form of obstacles to its normal filling.