Custom function not running on form submit


#1

Hi, I wanted to send a custom trigger to GTM when I submit my form. For the same reason, I am using the following script

<script>

    $( "form" ).submit(function( event ) {
     
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({
        'event' : 'formSubmissionSuccess',
        'formId' : 'contactForm'
      });
      
    });
   </script>

I’ve tried to save my script in head HTML, footer HTML and in a custom HTML right below the form. I’ve also tried to replace the “form” selector with Form id but the function still wouldn’t run. Kindly help me run this function on form submission.

My main goal is to track Hubspot form submission in GTM and GA. Kindly help me do so


#2

Hi @Harshendra_Singh,

The reason for your code not executing is because of the way jQuery works, and the way HubSpot forms work.

By the time this code runs, it is looking for all forms on the page and attaching the event handler to them.

The problem is that the HubSpot forms are loaded in after some delay, thus this event handler is not being attached.

I have responded to a similar question with the code that you will need.

In order for your code to execute, you will need to rely on bubbling, or if you have control over the form embed you can always use the onComplete function to send the code then.

hbspt.forms.create({
	portalId: '',
	formId: '',
	onFormSubmit: function($form) {
		window.dataLayer = window.dataLayer || [];
		
		window.dataLayer.push({
			'event' : 'formSubmissionSuccess',
			'formId' : 'contactForm'
		});
	}
});

Thanks


#3

Hi Stephen_Yager,
Thank you for such a quick reply. The post that you pointed to did help a lot. Referring to your answer, I did modify the code and It is firing an event to GTM. But the event is being fired on click of submit button even after the form is not validated.

I wanted to know if there is any way the function could be triggered on submit click after form validation without using the form embed.

Thanks again


#4

Hi @Stephen_Yager,
Thank you for such a quick reply. The post that you pointed to did help a lot. Referring to your answer, I did modify the code and It is firing an event to GTM. But the event is being fired on click of submit button even after the form is not validated.

I wanted to know if there is any way the function could be triggered on submit click after form validation without using the form embed.

Thanks again


#5

Hi @Harshendra_Singh,

With out seeing your code in action, it would be difficult give a better answer.

If you are using a HubSpot form embed code and you cannot modify the onFormSubmit function, the code in from the other post will be of more use since it does check for errors.

Could you please provide a link to your page or post some code so that I can give you a better solution?

Thanks