Pre-Populating Embedded Form Fields From The Query String

Written by Michael on October 2, 2009

Posted in Form Hacks

While we allow pre-population of form fields, using the JavaScript embed method while pre-populating fields is a bit inflexible by default. Wouldn’t it be nice if you could pre-populate fields in an embedded form via the query string (mimicking the behavior of non-embedded forms)? This has been a popular request recently, so I have written a simple, custom “JavaScript Embed” method that does just that:


<script type="text/javascript">

var form = “423214”; // replace this with your form’s id.
var viewkey = “aWhgE32sa3” // replace this with your form’s viewkey.

// build the url
var url = “http://www.formstack.com/forms/js.php?form=”;
url += form;
url += “&viewkey=”;
url += viewkey;
url += “&style_version=2”;
url += location.search.replace(‘?’,’&’);

// create the script element.
var s = document.createElement(‘script’);
s.setAttribute(‘type’,’text/javascript’);
s.setAttribute(‘src’, url);

// get the script’s ‘outer html’ and add it to the document.
var t = document.createElement(‘div’);
t.appendChild(s);
document.write(t.innerHTML);

</script>

To use the above script, you will need to modify the ‘form’ and ‘viewkey’ variables so that they are set to the form you wish to embed (if you don’t know how to find your form’s id and viewkey values, please view the link above). Then, simply copy and paste this script into your HTML, just like you would the regular embed code.

After you embed the script, simply append data to the query string to ensure that the fields are pre-populating. For instance, if I have a name field on my form with the label ‘name’, I could pre-populate it by the following url:

http://www.example.com?name-first=foo&name-last=bar

In review, while pre-populating embedded forms with the default embed script is possible, it can be inflexible in certain situations. In these situations the above JavaScript can make the pre-population more dynamic by populating form fields from data in the query string.

Update: After I wrote this blog post, I discovered that this method no longer works in IE for most forms, due to how IE fetches and loads external JavaScript files. We recommend (and only support) the pre-population methods found here. If you do try and use the embed method outlined in this post, be sure to test in IE.