How Do I Prepopulate a Form Field Based On Previous Page Input?

December 13, 2017

In this scenario, say you have a newsletter signup form on your homepage with one single email field to fill out. On submit of this field you would like the user to be sent to a new page with a slightly longer form to fill out. However, you don’t want them to have to fill out their email again.

The following solution uses url parameters to send the data where it needs to be on the new page.

Form HTML

Send form data to new page with url parameters:

<form class="newslettersignup__home" id="newslettersignup__home" method="GET" action="/newsletter-signup">
    <label for="newsletter__email">Enter Your Email</label>
    <input placeholder="Enter your email" id="newsletter__email" type="email" name="newsletteremail" />
    <input type="submit" value="Sign Up" />
</form>

JavaScript

On load of new page use url parameters to update the value of the correct fields:

function querySt(attribute) {
    url = window.location.search.substring(1);
    substrings = url.split('&');
    for (i=0;i<substrings.length;i++) {
        ft = substrings[i].split('=');
        if (ft[0] == attribute) {
            return ft[1];
        }
    }
}

//only execute if on the newsletter-signup page (change to your url)
if(window.location.href.indexOf("newsletter-signup") > -1) {

   var newsletteremail = querySt('newsletteremail');
   newsletteremail = decodeURIComponent(newsletteremail);

   if(newsletteremail !== 'undefined'){
       document.getElementById('newsletteremail').value = newsletteremail;
   } else {
       document.getElementById('newsletteremail').value = '';
   }
}

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive