• Courses
    • Courses
    • Course bundles
  • Blog
  • Services
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • About
    • About
    • Contact
  • Login
  • Courses
    • Courses
    • Course bundles
  • Blog
  • Services
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • About
    • About
    • Contact
  • Login

February 20, 2017

Form Abandonment Tracking With Google Tag Manager

Form abandonment tracking is extremely useful for conversion rate optimization. Not only can form analysis give you data on drop-offs but you’ll have information on user behavior in each field of the form. By measuring field abandonment you get a greater depth of insight into exactly why users are leaving your form. In this blog post I’ll show (1) how you can track form engagement with Google Tag Manager, (2) pass that data to Google Analytics, and (3) case study of how I implemented form abandonment tracking in practice.

There are existing solutions (like Zuko) that do this in a much more elegant manner (compared to GA), with reports dedicated specifically to form analytics. Think of it like the goal funnel visualization reports, but applied to forms.

If you have a budget, I’d recommend using already existing paid solutions. However, if you don’t have it, or just want to keep all data in one place (i.e., Google Analytics), continue reading.

In this blog post:

  • You’ll learn how to track form abandonment with Google Tag Manager.
  • You’ll learn to send form abandonment data to Google Analytics.
  • I’ll show you when form abandonment tracking does not work.
  • I’ll show you a quick case study how form abandonment tracking can be implemented via GTM in not-so-perfect real-life situation.

Form Abandonment Listener

Simo Ahava wrote the script (that was later updated by Lauri Pisspanen) that automatically tracks form abandonment (even if there are multiple forms on the same page). If the form is abandoned (i.e. visitor proceeded to another page or closed browser tab), this script (a.k.a. listener) will fire a dataLayer event. That event will show us which fields did the visitor interacted with. This is done as a trail that might look like this:

firstName > lastName > address > creditCardNumber

The example above shows that the Credit Card Number field was the last one which was filled by a visitor, meaning that the next form field is probably responsible for the bounce. If the visitor clicks submit, then form abandonment event will not be created (but there are some limitations – keep reading!)

Keep in mind that Lauri’s form abandonment listener will not track the exact history of interaction. If visitor filled in lastName field and then returned to firstName field, this interaction will not be displayed in GA event reports. Here’s a scheme which should help you better understand what data will be provided under different circumstances.

form abandonment scheme

As you can see in the image above, visitor jumped from First name field to Credit card number and then went back to Last. Nonetheless, the form abandonment listener returned value: Email > First Name > Last name > Credit card number.

 

So What’s The Plan?

  1. First, we need to create a custom HTML tag (withing Google Tag Manager) with form abandonment listener’s code. It should be fired only on those pages where you keep your forms (not All pages, because tag optimization is one of best GTM practices).
  2. That custom listener will fire a dataLayer event every time the form is abandoned, so we’ll need to “teach” Google Tag Manager to recognize that new data by creating Data Layer variables and custom trigger.
  3. Then we’ll create a Google Analytics Event tag that will transport the event metadata from Data Layer to Google Analytics servers.

 

Let’s create a Custom HTML Tag in Google Tag Manager

Open your GTM account and go to Tags, click Create new. Choose tag type Custom HTML and paste the following code snippet.

Note: The script below is upgraded! Simo Ahava’s/Lauri Piispanen’s script tracks only input fields, checkboxes, and radio buttons. The script in this blog post also tracks text areas and dropdowns. So make sure you’re using this one.

<script>
(function() {
  if (typeof document.querySelectorAll === "undefined") {
    return
  }
    window.addEventListener('beforeunload', function(e) {
      findUnsubmittedForms().forEach(function(it) {
        window.dataLayer.push({
          'event' : 'formAbandonment',
          'eventCategory' : 'Form Abandonment',
          'eventAction' : it.history.join(" > ")
        })
      })
    })

    var history = {}

    window.addEventListener("load", function() {
      document.addEventListener("change", function(e) {
        var target = e.target
        if (target && target.tagName && (target.tagName.toUpperCase() == "INPUT" || target.tagName.toUpperCase() == "TEXTAREA" || target.tagName.toUpperCase() == "SELECT")) {
          var inputName = target.getAttribute("name")
          var form = target.form
          if (form && inputName) {
            var formName = form.getAttribute("name")
            if (typeof history[formName] == "undefined") {
              history[formName] = []
            }
            if (history[formName].slice(-1) != inputName) {
              history[formName].push(inputName)
            }
          }
        }
      })
    })

    function findUnsubmittedForms() {
      return Object.keys(history).filter(hasNoFormSubmitEvent(window.dataLayer)).map(findFormFromHistory).filter(notEmpty)
    }

    function hasNoFormSubmitEvent(dataLayer) {
      return function(name) {
        return dataLayer.filter(isFormSubmitEvent).map(getFormName).indexOf(name) == -1
      }
    }

    function isFormSubmitEvent(e) {
      return e.event === 'gtm.formSubmit'
    }

    function getFormName(e) {
      return e['gtm.element'].name
    }

    function findFormFromHistory(name) {
      return {
        name: name,
        history: (history[name] || [])
      }
    }

    function notEmpty(form) {
      return form.history.length > 0
    }

})()
</script>

 

In triggering section (of a tag) click a button with Plus icon (Create new trigger).

Plus button - create new trigger

Enter the following settings:

  • Title – Pageview – Contact page (adjust the title to the page where your form is placed).
  • Trigger type – Pageview
  • This trigger fires on – Some Page Views
  • Rule: Page Path contains /contact-us.
    Instead of /contact-us you should enter the address of the page where your form is. If your website is on multiple domains, I’d recommend using Page URL instead of Page Path.

Trigger - Contact page

Save both the trigger and the tag. At this point testing is not possible yet, because form abandonment event will be fired only when you close browser tab or navigate to another page, thus GTM Preview and Debug console will not show anything. Continue reading and I’ll show you how to test everything.

 

Create Trigger and Data Layer Variables

Before we create the Universal Analytics event tag, you’ll need to create a Custom Event Trigger and two Data Layer Variables.

Form abandonment listener will push a dataLayer event formAbandonment into the Data Layer once a form is abandoned:

dataLayer.push({
 'event': 'formAbandonment',
 'eventCategory': 'Form Abandonment',
 'eventAction': 'fields that were filled by a visitor'
});

As you can see in the example above, formAbandonment event contains two variables – eventCategory and eventAction. This metadata is really valuable, so let’s transfer it to Google Analytics!

We can use formAbandonment event as a custom trigger, which looks like this:

formAbandonment trigger

 

And the two Data Layer Variables should look like this:

dlv- eventAction

dlv- eventCategory

 

 

Let’s Send Data To Google Analytics!

Next, onto the Event Tag itself:

  • Choose Tag Type – Universal Analytics
  • Enter Google Analytics Tracking ID
  • Choose Tracking Type – Event
  • Fill in Event Category and Action fields with newly created Data Layer variables.
  • I’ve set the Non-Interaction field to True, since this isn’t really a user interaction but more like metadata about the page view, but you can do as you wish.
  • Important: go to More Settings -> Fields to Set, and add the following:
    • Field Name: transport
    • Value: beacon (this feature will send the data when user abandons the form)

Google Analytics Event tag - Form abandoned

 

And don’t forget to assign the formAbandonment custom trigger to this Google Analytics Event tag.

In conclusion:

  • Form abandonment listener spots that visitor abandons the form, and then fires dataLayer event with eventCategory and eventAction.
  • The dataLayer event triggers Google Analytics Event tag and values of eventCategory and eventAction are transferred to GA servers.

 

Testing

Enable GTM’s Preview and Debug mode  (if it’s not working, check out 10 ways how to fix the P&D mode) and refresh the page where your form is located. Fill in several fields (but not all) and then close browser tab. Then open GA Real-time event reports and click “Events (Last 30 min)”, because non-interaction events are displayed only in this section of real-time reports.

That’s it! You’re good to go!

Success

If the event did not appear, read the next chapter of this blog post. I also recommend checking most common Google Tag Manager mistakes.

 

This Form Abandonment Tracking isn’t Working For me, why?

If you have tried tracking forms before, then you already know it might be a real pain in the ass sometimes. The fact that there are at least 5 form tracking methods with GTM just proves my point. Form abandonment tracking is no exception.

The main problem with form tracking via Google Tag Manager is that there are no global standards of how forms must be developed. Some developers may prefer one technology (e.g. AJAX) over another – and they have a full right to do so. Just remember – there is no “one method to track them all”.

These are the reasons why form abandonment tracking probably did not work for you:

 

#1. Unsupported Browser

A visitor must use Chrome, Firefox, Microsoft Edge, Opera or modern Android browser. Safari (even on iOS) and Internet Explorer do not support this feature, thus their form abandonment will not be tracked. Here’s a full list of (un)supported browsers.

 

#2. <form> tag

A form must be developed using <form> HTML tag. I have seen forms, which use only <div>, thus could not be tracked with this listener. You can check this by inspecting the form.

form tag highlighted

 

#3. “Name” Attribute

Each input field of the form must contain “name” attribute (in order to track form field titles).

name attribute

Or you’ll need to edit form abandonment listener’s code. Since I am not very Javascript-savvy (and don’t want to break the entire website), I choose not to edit it. If you have access to developers, as them to help you edit the code.

 

#4. Valid form “Submit” event

The form must dispatch a valid form submit browser event. Simo Ahava’s/Lauri Piispanen’s form abandonment script listens for browser submit event – if it occurs, the script won’t fire form abandonment event.

If your form is built with AJAX, then form abandonment listener will fire event if there was a successful form submission.

In this blog post, I’ll show you a case study with this very same problem when a form does not dispatch a valid submit event, and how the problem can be solved.

Now let’s see the Form Abandonment Tracking listener in action (case study).

 

Case Study

Context

This blog post was inspired by my fellow Nathan Hague who asked for a form tracking advice. Instead of giving him a direct answer, I decided to publish a blog post. Nathan, I hope you’ll find this useful, mate.

Nathan’s client Epic Charters offers tours with private Luxury Sailing Yachts, Catamarans, Motor Boat Charters for Day Trips, Overnight and Extended cruising around Phang Nga Bay, Krabi, Phi Phi Islands, Racha Islands, Phuket, and the Andaman Sea.

In their website, you’ll see a catalog of various boats. Each one of them has a dedicated Enquiry button which opens a form. Nathan asked me if I could track abandonment of these forms and push data to Google Analytics.

So let’s see what I could do about it.

 

Investigation

Every Google Tag Manager implementation requires an investigation first. I created a test GTM container, added (1) custom HTML tag with Form Abandonment listener, two Data Layer variables ((2) eventAction and (3) eventCategory), (4) custom trigger (formAbandonment) and (5) Google Analytics Event tag. With the help of Tag Manager Injector (Chrome extension) I injected my GTM container’s Javascript code into Epic Charters website’s source code (but only within my browser; other website visitors were not affected).

Next step is Preview and Debugging. After I enabled P&D mode in Google Tag Manager and refreshed the Epic Charters page, a Preview and Debug console appeared. As you can see in the image, form abandonment tracking tag fired, so I am ready to start testing (this means that a listener is now monitoring abandoned forms on a website).

Tag fired

 

After clicking Enquiry button I filled in two first form fields, closed browser tab and immediately opened Google Analytics real-time reports. This is what I saw:

Google Analytics real-time reports

Awesome! This is a good start since my Form abandonment event was captured. As you can see in the image above, Event Action value shows that a visitor (me) managed to fill the first two form fields and then bounced (or navigated to another page on Epic Charters website).

Form field names were captured properly because they all have “name” attribute:

inspect form - name attribute

Also, this form is built using <form> HTML tags which is also a requirement for this form abandonment listener to work:

form tag

P.s. this “tag” has nothing to do with “GTM tag”

 

Problems

However, not everything is perfect here. There are several problems:

  1. This form does not fire a valid form submit an event. Instead, it redirects a user to a “Thank you” page. This means, that even after successful form submission the Form abandonment event will be sent to GA anyway.
  2. I could not find an easy way to differentiate (within GTM) which form was abandoned. Since there are multiple forms on the same page, this data is crucial in analytics reports.

 

How To Fix it?

Both aforementioned problems should be solved by the developer. As I have already mentioned it in my previous blog post 22 Google Tag Manager best practices, developers are not your enemies. It’s OKAY to ask for their help.

 

Solution to Problem No.1

In order to avoid false Form abandoned events, a form must dispatch a valid Form Submit browser event. It’s the same event that is required for GTM form auto-event listener to work. In other words, if GTM default form tracking triggers don’t catch your form submissions, then Form abandonment listener will send you false Form Abandonment events. To sum up, a developer will have to edit the form’s source code accordingly.

 

Solution to problem No.2

The best way (in my opinion) to track which form was abandoned is to ask the developer to fire a dataLayer.push event (with additional metadata) every time a visitor opens an inquiry form.

dataLayer.push({
 'event': 'enquiryFormOpened',
 'product': 'Luxury Power Boat'
});

“product” variable’s value should change dynamically based on which product’s form is opened.

Then, I’d create a Data Layer variable product in Google Tag Manager and add it to Google Analytics Event tag as Event Label. It should look like this:

Upgraded Google Analytics Event tag - Form abandoned

The result? Each form abandonment event in Google Analytics would also have a particular product as event label, thus I could analyze which product forms are abandoned most often.


 

Conclusion

So there you have it – an extensive guide on how to track from abandonment with Google Tag Manager and pass that data to Google Analytics. Personally, If there is a budget, I’d rather choose ready-made paid solutions (like Hotjar) which are created specifically for this purpose and track forms in a much more elegant manner (compared to GA), with reports tailored specifically to form analytics.

However, if you don’t have it, or just want to keep all data in one place (i.e., Google Analytics), feel free to do to so:

  • Add custom HTML tag to Google Tag Manager and paste the form tracking script that I have posted in this blog post.
  • Create Data Layer variables, trigger and Google Analytics event tag.

Every time someone starts filling in your form and then closes the browser tab or navigates to another page, form tracking script will fire a GA event.

But not everything is so easy. The main problem with form tracking is that there are no global standards of how forms must be developed. Some developers may prefer one technology (e.g. AJAX) over another – and they have a full right to do so. But remember – there is no “one method to track all forms”.

The form tracking method described in this blog post will not work if:

  • The form is not created by using <form> HTML tags.
  • The form is using AJAX, form abandonment events will be sent to Google Analytics even if the form has been successfully submitted.
  • Form fields do not have “name” attribute.

This form abandonment tracking script was originally created by Simo Ahava (updated by Lauri Piispanen) and was automatically tracking input fields, checkboxes and radio buttons. My co-worker (developer) slightly upgraded it and added support for text areas and dropdowns.

So if you need support for all aforementioned fields, use the script from this blog post.

If you have questions, feel free to post a comment below.

Julius Fedorovicius
In Form Tracking Google Analytics Tips Google Tag Manager Tips
18 COMMENTS
Erdem
  • Mar 14 2017
  • Reply

very helpful guide. thanks a lot.

Brendan
  • Mar 17 2017
  • Reply

Thanks for the script and trouble shooting aspect.

I had a question though, I've noticed that this doesn't capture any drop-down menus and we work with a lot on our forms. Do you know if there's a way to build the functionality to read if someone has interacted with a drop-down form? I'm pretty new to jQuery so not sure how to execute that.

    Julius Fedorovicius
    • Mar 18 2017
    • Reply

    Hi Brendan,

    Apparently in some forms dropdown interactions are not recognized (I just tested this myself with several forms). The reason is still unknown to me, I will take a closer look at it and will let you know.

    Julius Fedorovicius
    • Mar 20 2017
    • Reply

    I have found out, why dropdowns are not tracked in some forms. Double check if your form's dropdowns contain "name" attribute (e.g. name="country"). You can do that by clicking "Inspect element" upon the form field.

    As it is mentioned in this blog post, there are no standards how forms should be developed. Apparently sometimes not all form fields in the same form can have a "name" attribute.

    In this case you should ask your developers to add "name" attributes to all form fields.

    If this explanation does not apply to your issue, give me a URL of a page with form and I'll take a look.

      Brendan
      • Mar 20 2017
      • Reply

      Hi, thanks for the follow up! I looked at it again today and realized it was still pulling the original script Lauri Piispanen created that only targeted Input and not Select as well. Once I refreshed with new script it worked great!

        Julius Fedorovicius
        • Mar 21 2017
        • Reply

        Great!

Roberto
  • Aug 9 2017
  • Reply

Hello, I follow your guide but doesn't work very well, I put all have you put in the guide but still doesn't work, could you help me please to set it up.

I don't understand where it can place this code (inside the signup page);

Before we create the Universal Analytics event tag, you’ll need to create a Custom Event Trigger and two Data Layer Variables.

Form abandonment listener will push a dataLayer event formAbandonment into the Data Layer once a form is abandoned:

dataLayer.push({
'event': 'formAbandonment',
'eventCategory': 'Form Abandonment',
'eventAction': 'fields that were filled by a visitor'
});

Please help me out

    Julius Fedorovicius
    • Aug 9 2017
    • Reply

    Hey,

    The method works well but under very specific circumstances.

    You don't have to place any code to the signup page.

    dataLayer.push({‘event’: ‘formAbandonment’}) is already in the Form Abandonment Listener that I've described in this blog post.

    Remember that large piece of code that you added to a custom HTML tag? That is form abandonment listener.

    If the listener captures form abandonment, it will fire a dataLayer.push event (formAbandonment) with two data points: eventAction and eventLabel. Then, you'll need to create two variables in GTM in order to transfer them to the Universal Analytics event tag.

    This tracking method only works if:
    - Visitor is using Chrome, Firefox, Microsoft Edge, Opera or modern Android browser
    - A form must be developed using

    HTML tag.
    - A form must dispatch a valid "form submit" event. AJAX forms are not supported by this technique.
    - Every form field must have "name" attribute.
    ALL these 4 conditions must be satisfied.

    Hope this answers your question. If not, drop me a link to the form and I'll check it out.

      Roberto
      • Aug 9 2017
      • Reply

      Hello, thanks for answers so quickly.

      I only ask because I was wondering If I miss something.

      I follow all your step by step and study each of all configuration to understand how it works. But when I tried in Google Analytics Real time Reports dosen't see the event.

      This is the website I am working on it: https://mybookie.ag/signup.php

      Thanks, for your help.

      Regards, Roberto.

        Julius Fedorovicius
        • Aug 9 2017
        • Reply

        This form abandonment tracking technique will not work for you because that form is not created using

        tag.

        As I have mentioned in my blog post, it is one of the requirements for the listener to work.

        My JavaScript knowledge is pretty limited so, unfortunately, I cannot help you here.

          Roberto
          • Aug 9 2017

          Hello Julius, thanks for the check it this. Don't worry about your javascript limitations I go it too.

          Could please copy paste code here, where is not created by form tag elements because I set it to the task with how you mention in your blog post, and for me it is strange.

          Thanks, Roberto.

          Julius Fedorovicius
          • Aug 15 2017

          Hey, sorry for getting back to you so late. I've just downloaded this form abandonment recipe, imported it to the clean GTM container and tried abandoning your form. Everything worked and I saw the form abandonment event in my Google Analytics Real-time event reports.

          Have you tried importing the recipe? I abandoned your form with Google Chrome.

          Also, please describe the exact workflow of your actions (step-by-step instruction how are you abandoning your form). Maybe there's something else I am not aware of.

Roberto
  • Aug 15 2017
  • Reply

Thanks, Julius, I will try and send to you.

Regards, Roberto

Jerome
  • Feb 12 2018
  • Reply

Thanks Julius !
I have tried on mobile but the script doesn't work. Do you have an idea ?

    Julius Fed
    • Feb 12 2018
    • Reply

    Hey, as far as I know, this should work only on mobile. And unfortunately, I do not have a solution for mobile users.

Heli
  • Mar 14 2018
  • Reply

Hi Julius,
I added your HTML tag to GTM and it works otherwise but also fires when the form is submitted. I checked for gtm.formSubmit and this takes place - is there anything else that could cause this?
Thanks in advance!

andrew
  • Apr 23 2018
  • Reply

hey julius!

i have this script up and running, and like Jerome, i am not able to get this going on iphone / tablets ... i looks like it is an issue with iOS ... i am able to get this running on android devices, however

do you know of any issues with iOS and other scripts? thanks for any / all of your help!!

    Julius Fed
    • Apr 23 2018
    • Reply

    Sorry, I don't have a script for mobile devices.

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *

 

Hi, I'm Julius Fedorovicius and I'm here to help you learn Google Tag Manager and Google Analytics. Join thousands of other digital marketers and digital analysts in this exciting journey. Read more
Analytics Mania
  • Google Tag Manager Courses
  • Google Tag Manager Recipes
  • Google Tag Manager Resources
  • Google Tag Manager Community
  • Login to courses
Follow Analytics Mania
  • Subscribe to newsletter
  • RSS feed
Recent Posts
  • 23 Key Benefits of Google Analytics 4
  • 10 Google Analytics 4 Mistakes in Configuration You Should Avoid
  • Two Link Click Events in Google Tag Manager Preview Mode
Analytics Mania - Google Tag Manager and Google Analytics Blog | Privacy Policy
Manage Cookie Settings