Skip to content

Instantly share code, notes, and snippets.

@JeffTD
Created February 10, 2018 00:28
Show Gist options
  • Select an option

  • Save JeffTD/a0d212b3813c5903f072f812f9b068e8 to your computer and use it in GitHub Desktop.

Select an option

Save JeffTD/a0d212b3813c5903f072f812f9b068e8 to your computer and use it in GitHub Desktop.
JS to scrape URL for UTM parameters and inject into form inputs
<!-- inputs - replace these exmaples with the custom fields for your nation -->
<input type="text" id="utmCampaign" />
<input type="text" id="utmSource" />
<input type="text" id="utmMedium" />
<input type="text" id="utmContent" />
<input type="text" id="utmTerm" />
<script>
// Parse URL Queries Method - this scrapes the URL
(function($){
$.getQuery = function( query ) {
query = query.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var expr = "[\\?&]"+query+"=([^&#]*)";
var regex = new RegExp( expr );
var results = regex.exec( window.location.href );
if( results !== null ) {
return results[1];
return decodeURIComponent(results[1].replace(/\+/g, " "));
} else {
return ;
}
};
})(jQuery);
// Document load - this injects the utm parameters scraped from the URL into the form fields based on their ID.
$(function(){
var utmCampaign = $.getQuery('utm_campaign');
$("#utmCampaign").val(utmCampaign);
var utmSource = $.getQuery('utm_source');
$("#utmSource").val(utmSource);
var utmMedium = $.getQuery('utm_medium');
$("#utmMedium").val(utmMedium);
var utmContent = $.getQuery('utm_content');
$("#utmContent").val(utmContent);
var utmTerm = $.getQuery('utm_term');
$("#utmTerm").val(utmTerm);
});
</script>
@JeffTD
Copy link
Author

JeffTD commented Feb 10, 2018

This snippet can be paired with custom fields to allow for UTM parameters in URLs to be submitted with NationBuilder forms. I'd recommend setting a display:none; rule on your custom fields to prevent this process from being visible to the end-user.

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