Passing URL String Variables to Prefill an Ontraport Form

If you are using the “Javascript Snippet” method of getting a Ontraport Smart form onto your WordPress page and want to automatically fill in a field on the form (e.g., firstname) using a URL string variable (e.g., ?fn=John), I got it to work using the following Javascript:

<script>
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
window.onload = setVar;
function setVar() {
var theform = document.getElementsByTagName("form");
theform[0].elements["firstname"].value=getParameterByName("fn");
}
</script>

Note: this assumes there’s one form on the page. If there are multiple forms on the page, the first one is referenced by theform[0], the second one by theform[1], etc.

Note 2: works with both visible and hidden form fields (I’m actually using it with a hidden field).

Note 3: make sure to put this script in the HEAD section of the page.

3 Replies to “Passing URL String Variables to Prefill an Ontraport Form”

  1. I recently discovered the script I reference in this post wasn’t working in Microsoft Edge 42.17134.1.0. So I tested some other scripts for parsing URL parameters and found that the following script worked, even in Microsoft Edge:

    <script>
    var getQueryString = function ( field, url ) {
    var href = url ? url : window.location.href;
    var reg = new RegExp( ‘[?&]’ + field + ‘=([^&#]*)’, ‘i’ );
    var string = reg.exec(href);
    return string ? string[1] : null;
    };
    window.onload = setVar;
    function setVar() {
    var theform = document.getElementsByTagName("form");
    theform[0].elements["firstname"].value=getQueryString("fn");
    }
    </script>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.