Shoora
10/18/2018 - 12:02 PM

Simple script that finds all empty fields, adds their names to a string, sends value to google analytics via a custom event on page leave.

Simple script that finds all empty fields, adds their names to a string, sends value to google analytics via a custom event on page leave.

	var handleFormAbandonment = {

		form: $("form.your-form"),
		fields: 'input, select, textarea',
		emptyFields: '',
		init: function() {
			this.clickEvents();
			this.clearOnSubmit();
			this.submitOnPageLeave();
		},
		clickEvents: function() {
			var self = this;
			this.form.find(this.fields).on('click', function(){
				self.getAllEmptyFields();
			});
		},
		getAllEmptyFields: function() {
			var self = this;
			self.emptyFields = [];
			this.form.find(this.fields).each(function(){
				if( $(this).val() == '' ) {
					self.emptyFields += $(this).attr('name') + ', ';
				}
			});
		},
		clearOnSubmit: function() {
			var self = this;
			this.form.on('submit', function(){
				self.emptyFields = '';
			});
		},
		submitOnPageLeave: function() {
			var self = this;
			$(window).unload(function(e){
				// Send event to Google Analytics
			});
		}

	}