How to use JavaScript to fill a form on another page

You're trying to maintain state between pages. Conventionally there are two ways to maintain state:

  • Store state in cookies
  • Store state in the query string

Either way your first page has to persist state (to either cookies or the query string) and the other page has to - separately - restore the state. You can't use the same script across both pages.

Example: Using Cookies

Using cookies, the first page would have to write all the form data you'll need on the next page to cookies:

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With Cookies</title>
 </head>
 <body>
     <div>
         Setting cookies and redirecting...
     </div>
     <script>
         // document.cookie is not a real string
         document.cookie = 'form/title=My Name is Richard; expires=Tue, 29 Aug 2017 12:00:01 UTC'
         document.cookie = 'form/text=I am demoing how to use cookies in JavaScript; expires=Tue, 29 Aug 2017 12:00:01 UT';
         setTimeout(function(){
             window.location = "./form-cookies.html";
         }, 1000);
     </script>
 </body>
</html>

... and the second page would then read those cookies and populate the form fields with them:

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With Cookies</title>
 </head>
 <body>
     <form id="myForm" action="submit.mumps.cgi" method="POST">
         <input type="text" name="title" />
         <textarea name="text"></textarea>
     </form>
     <script>
         var COOKIES = {};
         var cookieStr = document.cookie;
         cookieStr.split(/; /).forEach(function(keyValuePair) { // not necessarily the best way to parse cookies
             var cookieName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
             var cookieValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
             COOKIES[cookieName] = cookieValue;
         });
         document.getElementById("myForm").getElementsByTagName("input")[0].value = COOKIES["form/title"];
         document.getElementById("myForm").getElementsByTagName("textarea")[0].value = COOKIES["form/text"];
     </script>
 </body>
</html>

Example: Using the Query String

In the case of using the Query String, the first page would just include the query string in the redirect URL, like so:

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With The Query String</title>
 </head>
 <body>
     <div>
         Redirecting...
     </div>
     <script>
         setTimeout(function(){
             window.location = "./form-querystring.html?form/title=My Name is Richard&form/text=I am demoing how to use the query string in JavaScript";
         }, 1000);
     </script>
 </body>
</html>

...while the form would then parse the query string (available in JavaScript via window.location.search - prepended with a ?):

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With The Query String</title>
 </head>
 <body>
     <form id="myForm" action="submit.mumps.cgi" method="POST">
         <input type="text" name="title" />
         <textarea name="text"></textarea>
     </form>
     <script>
         var GET = {};
         var queryString = window.location.search.replace(/^\?/, '');
         queryString.split(/\&/).forEach(function(keyValuePair) {
             var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
             var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
             GET[paramName] = paramValue;
         });
         document.getElementById("myForm").getElementsByTagName("input")[0].value = GET["form/title"];
         document.getElementById("myForm").getElementsByTagName("textarea")[0].value = GET["form/text"];
     </script>
 </body>
</html>

Example: With a Fragment Identifier

There's one more option: since state is being maintained strictly on the client side (not on th server side) you could put the information in a fragment identifier (the "hash" part of a URL).

The first script is very similar to the Query String example above: the redirect URL just includes the fragment identifier. I'm going to re-use query string formatting for convenience, but notice the # in the place where a ? used to be:

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With The Fragment Identifier</title>
 </head>
 <body>
     <div>
         Redirecting...
     </div>
     <script>
         setTimeout(function(){
             window.location = "./form-fragmentidentifier.html#form/title=My Name is Richard&form/text=I am demoing how to use the fragment identifier in JavaScript";
         }, 1000);
     </script>
 </body>
</html>

... and then the form has to parse the fragment identifier etc:

<!DOCTYPE html>
<html>
 <head>
     <title>Maintaining State With The Fragment Identifier</title>
 </head>
 <body>
     <form id="myForm" action="submit.mumps.cgi" method="POST">
         <input type="text" name="title" />
         <textarea name="text"></textarea>
     </form>
     <script>
         var HASH = {};
         var hashString = window.location.hash.replace(/^#/, '');
         hashString.split(/\&/).forEach(function(keyValuePair) {
             var paramName = keyValuePair.replace(/=.*$/, ""); // some decoding is probably necessary
             var paramValue = keyValuePair.replace(/^[^=]*\=/, ""); // some decoding is probably necessary
             HASH[paramName] = paramValue;
         });
         document.getElementById("myForm").getElementsByTagName("input")[0].value = HASH["form/title"];
         document.getElementById("myForm").getElementsByTagName("textarea")[0].value = HASH["form/text"];
     </script>
 </body>
</html>

And if you can't edit the code for the form page

Try a greasemonkey script.


It is a good place to use cookies

Ex: From quirksmode.org

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

and a side note, you can use the onload event to know when the page is ready

<script language="javascript"> 

function setTitle(){
    var title = prompt("Field Info","Default Value");
    var form = document.form[0];
    form.elements["fieldName"].value = title;
}

windows.onload = setTitle;

</script>

If it would be possible to manipulate target websites without access to the target's system/source/mitm-methods then this would really be an open highway for malware in combination with clickjacking! I do not want your script to tell the form of my bank what to do. ;-)

Use some kind of automation tools like AutoIt (www.autoitscript.com) for this purpose. Easy to learn and it hast good Form integration. If standard is not enough, look for UDFs like winhttp for AutoIt.