Created
December 2, 2014 17:03
-
-
Save alexbaulch/45a9f2752ad0d99a8853 to your computer and use it in GitHub Desktop.
Check form to which fields have been filled in before a user abandons it and send the fields to Google Analytics.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// stuff to do before the page un loads | |
if ( $('[data-page-name="contact"]').length ) { | |
var count = 0; | |
window.onbeforeunload = function(e) { | |
var contactUsForm = $('[data-page-name="contact"]').find('.contact-us-form'); | |
var requiredFields = contactUsForm.find('[data-val-required]'); | |
var completedFields = []; | |
var missedFields = []; | |
$.each(requiredFields , function(index, formField) { | |
if ( $(formField).is('input[type=text]') || $(formField).is('textarea') ) { | |
if ($(formField).val() !== '') { | |
completedFields.push( $(formField).siblings('label').text().trim() ); | |
} | |
else { | |
missedFields.push( $(formField).siblings('label').text().trim() ); | |
} | |
} | |
else if ( $(formField).is('select') ) { | |
if ($(formField).val() !== '') { | |
completedFields.push( $(formField).parent().siblings('label').text().trim() ); | |
} | |
else { | |
missedFields.push( $(formField).parent().siblings('label').text().trim() ); | |
} | |
} | |
}); | |
if (completedFields.length !== requiredFields.length) { | |
var flattenedCompletedFields = completedFields.toString(); | |
var flattenedMissingFields = missedFields.toString(); | |
_self.trackThisBounceRateCalculationUnaffected({ | |
category:'Contact', | |
action: 'Abandoned', | |
label: 'Completed fields: ' + (completedFields.length === 0 ? 'None' : flattenedCompletedFields) + '. Missing fields: ' + flattenedMissingFields | |
}); | |
return false; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment