Query Variables into Form Fields

Occasionally I run across the situation where I need to grab query variables on a page load and stuff them into hidden fields on a form. It’s most common in marketing, particularly in either social or ad tracking.

Every now and then I’ll tell someone about it and they get excited. It’s only a single line of code you drop on your site and it works for every form. And yet, I somehow keep forgetting to save the code. So I end up rewriting it each time.

Well, I’m done with that. Here’s the code:

    var qs=function(e){if(""==e)return{};for(var t={},o=0;o<e.length;++o){var n=e[o].split("=",2);1==n.length?t[n[0]]="":t[n[0]]=decodeURIComponent(n[1].replace(/\+/g," "))}return t}(window.location.search.substr(1).split("&")),f=document.forms;for(x in f)for(item in qs)this.form.elements[item].value=qs[item],console.log(item);

All you have to do is drop that code in the footer of your page and it’ll work it’s magic. Do be aware that it will attempt to apply the query variables to every form on the page – main form, newsletter subscribe form, etc – if the query variable is equal to the name of a form field.

A few notes:

  • If the form field name equals the query variable, the field will be updated with the query variable value.
  • Make sure the script runs after the forms you want filled.