Attach onFormSubmit function after form create?


#1

Hi everyone,

a quick question: is it possible to attach a onFormSubmit callback after the form has been created? That is, instead of

<script>
    hbspt.forms.create({ 
        portalId: 'XXX',
        formId: 'YYY',
        onFormSubmit: function($form) {...}
    });
</script>

define the onFormSubmit in a second moment and attaching it to the form?

<script>
    hbspt.forms.create({ 
        portalId: 'XXX',
        formId: 'YYY'
    });
    
    var myForm = $([something which will identify my form]);
    myForm.onFormSubmit = function($form) {...}
</script>

Thank you in advance,

Leonardo


#2

Hi @leonardo.scattola

Currently the onFormSubmit function only works when it’s part of the hbspt.forms.create() call, so it can’t be attached after the form is already loaded.


#3

Thank you @dadams for the quick answer. Will this scenario be supported in the future? Our need is to intercept a HS form submission on the page and perform another AJAX call, concurrent to the HS one; we couldn’t have control on the page (it would be provided by a customer), so our possibility would be to attach the submission listener after the page has been loaded.

Thank you,

Leonardo


#4

No specific plans to allow something like that at the moment, but I’ll pass this along to our Forms team to see if it’s something that we could add.


#5

Hi @leonardo.scattola,

Here is a work around for this, this will rely on jQuery and bubbling but should allow you to intercept the form submit:

/*
 * This code relies on bubbling and the use of the default HS error messages.
 * If you change the default class of the errors, or hide them all together, then the code will not fire.
 */

$(document).ready(function() {
	/* We will rely on bubbling to handle this */
	$('div.hs_submit').on('click', 'input[type="submit"]', function(){
		/* Make sure there are no errors visible on the page, only way to prevent false submits */
		if ( $('.hs-error-msgs:visible', this).length < 1 ) {
			// DO SOMETHING HERE
		}
	});
});

How to return an error in custom hubspot.create.form script