Adding onClick button event code


#1

Hello,

I need help with figuring out how to add onclick button event code to a submit button on the HubSpot form. I noticed that I can't access the button with JS. I tried adding an attribute of onClick but it didn't work for items within the shortcode - like submit button.

I found this conversation: Trigger Google Analytics Event with Form Submission and I tried the below code but it didnt work.

The onclick button event code I have looks like this:
onclick="dataLayer.push({'event': 'Newsletter', 'eventCategory': 'email', 'eventAction': 'submit'})"

Please help. I have no idea what I need to do here.

Any suggestions will be appreciated.

Best,
Helena


#2

Hi @Helena, since we can't alter the HTML of the submit button directly, we should be able to use the onFormSubmit callback function that's built into HubSpot forms. Reading through some docs, it looks like this would be your best method: https://developers.google.com/analytics/devguides/collection/analyticsjs/events

ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);

That code would go inside of the onFormSubmit callback like this:

hbspt.forms.create({
    css: ‘’,
    portalId: ‘XXXXXXX’,
    formId: ‘XXXXXXX-XXX-XXX-XXXXXXX’,
    onFormSubmit: function($form) {
        ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);
    },

Take a look at this thread for a bit more detail: Trigger Google Analytics Event with Form Submission


#4

This is very helpful. Thank you!