That is good to hear. Like I said, this was not a bullet proof way to do this. I have just come up with something else that might work. Try replacing this line:
if ( $('.hs-error-msgs:visible', this).length < 1 ) {
// ga send
}
With:
/* Make sure no error messages are showing up */
if ( $('.hs-error-msgs:visible', this).length < 1 ) {
var canSend = true;
/* Make sure each of the required fields have a value */
$.each( $(this).parent('form').find('input[required]'), function( i, v ) {
if( $.trim($(this).val()) === '' ) {
canSend = false;
}
});
if( canSend ) {
// ga Send
}
}
I have not tested this code, but what it should do is scan for all of the required fields and makes sure there is some value in them.
This does not take into account special validation rules like is a valid email, or valid phone numbers, but it should help prevent unwanted submissions.
Here is a bit of code that we use here at Salted Stone, it is dependent on jQuery, but could be adapted to other frameworks or vanilla js.
/*
* This code will allow you to do GA Event tracking on HS landing page using the Form Module:
* 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 it will not fire the GA event.
*/
$(document).ready(function() {
/* We will rely on bubbling to handle this */
$('div[id^="hs_form_target_module"]').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 ) {
ga('send', 'event', 'Form', 'Submission', 'Report');
}
});
});
This code above is for landing pages within HubSpot. To have the code fire on an embed code that you control, this would be a better option:
Hello,
Your solution gives me exactly what I am asked to do for the landing pages I got, but I discovered that the errors don’t get visible when the form is not submitted…
Is testing if the errors are showing the only way to do this?
This was the hack that we came up with as it was pretty reliable. I don’t think there was any other thing that we could hook into reliably. I might re-visit this and see if there is something else that we can look for. But like I said, this was the most reliable thing we could find.