Skip to content

Instantly share code, notes, and snippets.

@rezzz-dev
Last active August 4, 2020 18:58
Show Gist options
  • Save rezzz-dev/d189504e57e4cbb2ba304b0c1cb0640c to your computer and use it in GitHub Desktop.
Save rezzz-dev/d189504e57e4cbb2ba304b0c1cb0640c to your computer and use it in GitHub Desktop.
Injecting a hidden field into a ConvertKit form
<script>
// NOTES:
// 1. This only works for ConvertKit Forms that are embedded with HTML (not the JS method)
// 2. In order to save this as a cookie in the browser so that you can carry the across multiple pages, you'll need to include js-cookie (https://github.com/js-cookie/js-cookie). Otherwise it will only work on the page the visitor lands on.
// TIP: Create the custom field (in this example it's called trackingCode) in ConvertKit prior to running this, if not, CK will do it's best to create it, but may not be ideal case-sensitive or it may use spaces
jQuery(document).ready(function($) {
var hiddenField = Cookies.get('hiddenField') ? Cookies.get('hiddenField') : "";
if ( ! hiddenField ) {
hiddenField = ckGetQueryVariable('[val to store in custom field]');
if ( hiddenField ) {
Cookies.set('hiddenField', hiddenField, { expires: 30 }); //Optional
}
}
var utm_sent = Cookies.get('ck_sent');
if ( ( $(".seva-form").length > 0 ) && (utm_sent != "true") ) {
if ( hiddenField ) {
$("form").addClass('ext-ck'); // attach class to form to validate/future use
$("<input>").attr({
name: "fields[trackingCode]",
id: "fields[trackingCode]",
type: "hidden",
value: hiddenField
}).appendTo("form");
}
}
jQuery(document).on('click', '.formkit-submit', function() {
var utm_sent;
if (hiddenField) {
Cookies.remove('hiddenField');
Cookies.set('ck_sent', utm_sent, { expires: 365 } );
}
});
function ckGetQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){
return pair[1];
}
}
return false;
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment