Skip to content

Instantly share code, notes, and snippets.

@noahub noahub/form_submit.js
Last active Nov 28, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Jul 25, 2018

Mind if I submit some cleaned up and commented code?

@jacobheller

This comment has been minimized.

Copy link

commented Sep 4, 2018

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

This comment has been minimized.

Copy link

commented Sep 24, 2018

@skylarmb

This comment has been minimized.

Copy link

commented Oct 22, 2018

thanks @wgroth2!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.