Skip to content

Instantly share code, notes, and snippets.

@noahub
Last active November 28, 2018 18:26
Show Gist options
  • Save noahub/cab64fcf0b05ead054be1ecc01cf6fe9 to your computer and use it in GitHub Desktop.
Save noahub/cab64fcf0b05ead054be1ecc01cf6fe9 to your computer and use it in GitHub Desktop.
Fire Code on Form Submission
<script type="text/javascript">
//runs on form submission
function yourSubmitFunction(e, $) {
e.preventDefault();
try {
//ADD CUSTOM CODE HERE
}
catch(err) {
//code to handle errors. console.log is just an example
console.log(err);
}
finally {
// This submits the form. If your code is asynchronous, add to callback instead
gaForm(e);
lp.jQuery('.lp-pom-form form').submit();
}
}
//ga form submission event
function gaForm(event) {
var $form, $formContainer, params;
event.preventDefault();
event.stopPropagation();
$formContainer = lp.jQuery(event.currentTarget).closest('.lp-pom-form');
$form = $formContainer.children('form');
if ($form.valid()) {
if(typeof eventTracker !== 'undefined'){
if (!eventTracker._isGaLoaded()) {
return $form.submit();
}
params = lp.jQuery.extend({
category: 'Form',
action: 'Submit',
label: "#" + ($formContainer.attr('id'))
}, $formContainer.data('ubGAParams'));
eventTracker._logEvent(params);
return ga('send', 'event', params.category, params.action, params.label, {
hitCallback: function() {
return $form.submit();
}
});
}else{
return $form.submit();
}
}
};
//waits until window load to initialize
lp.jQuery(window).load(function(){
lp.jQuery(function($) {
$('.lp-pom-form .lp-pom-button').unbind('click tap touchstart').bind('click.formSubmit tap.formSubmit touchstart.formSubmit', function(e) {
if ( $('.lp-pom-form form').valid() ) yourSubmitFunction(e, $);
});
$('form').unbind('keypress').bind('keypress.formSubmit', function(e) {
if(e.which === 13 && e.target.nodeName.toLowerCase() !== 'textarea' && $('.lp-pom-form form').valid() )
yourSubmitFunction(e, $);
});
});
});
</script>
@BillRothVMware
Copy link

Mind if I submit some cleaned up and commented code?

@jacobheller
Copy link

I think line 14 (https://gist.github.com/noahub/cab64fcf0b05ead054be1ecc01cf6fe9#file-form_submit-js-L14) is unnecessary, since in the gaForm function we do $form.submit().

@wgroth2
Copy link

wgroth2 commented Sep 24, 2018

@skylarmb
Copy link

thanks @wgroth2!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment