26

I have a vanilla html page which has a form in it. A requirement has come in to be able to pre-populate the form via the url. Something like:

http://some.site.com/somePage.html?forename=Bob&surname=Jones

I can't seem to find any simple solution to this. Can someone point me in the right direction with some javascript to accomplish this? Happy to use a javascript solution, but I'd prefer to avoid pulling in an entire library just for this single use (none are currently used). Thanks.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Chris Knight
  • 24,333
  • 24
  • 88
  • 134

4 Answers4

28

Use a custom query string Javascript function.

function querySt(ji) {

    hu = window.location.search.substring(1);
    gy = hu.split("&");

    for (i=0;i<gy.length;i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}
var koko = querySt("koko");

Then assign the retrieved value to the input control; something like:

document.getElementById('mytxt').value = koko;
Cullub
  • 2,901
  • 3
  • 30
  • 47
Ian
  • 879
  • 8
  • 21
16

Are you using PHP? If so, that makes things much easier. Assuming your link as above, you can use:

<?php
$forename = $_GET['forename'];
$surname = $_GET['surname'];
?>
----------
<input id='forename' type='text' value='<?php echo $forename; ?>' >
<input id='surname' type='text' value='<?php echo $surname; ?>' >

That should pre-populate for you.

paradox870
  • 2,152
  • 4
  • 20
  • 30
  • It was not I who downvoted, but I'm afraid I'm not using PHP. – Chris Knight Mar 24 '11 at 18:43
  • Perhaps if paradox870 had prefaced his answer with something like "I see the person before me answered the method in javascript, but I would also like to point out that this can be performed in PHP .. in fact, here is a method to do so ...". I've found that stackoverflow users tend to get negative quickly if you try to help out more than the original question ... sometimes they go overboard. I can understand this i you don't first Answer the Question, but tell someone to do it another way, but in this case the question had actually Been Answered, and he was merely pointing out an alternative. – TheSatinKnight Mar 19 '15 at 03:05
  • 5
    The example is vulnerable to XSS: what happens if `$forename=="'><"`? – Marc Durdin Nov 14 '17 at 06:34
12
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for(var i = 0; i < hashes.length; i++)
        {
         hash = hashes[i].split('=');
         vars.push(hash[0]);
         vars[hash[0]] = hash[1];
         }

     return vars;
}

var get = getUrlVars();

//returns get['forename'] == bob; surname == jones
Chris Sobolewski
  • 12,819
  • 12
  • 63
  • 96
  • Thanks, I like the simple look of this. My javascript is a bit rusty. Can you briefly describe ``var vars = [],hash;``? – Chris Knight Mar 24 '11 at 18:46
  • 1
    that is simply declaring variables in a comma seperated list. vars = [] instantiates a new empty array, and hash is a seperate variable. just a shorthand way to declare 2 at once. – Chris Sobolewski Mar 24 '11 at 19:19
  • Ah, of course. I was mistakenly associating the ``hash`` with the ``[]``. – Chris Knight Mar 24 '11 at 19:41
  • Excellent! I had the exact same problem (had to pre-populate a form on a static HTML page) and this did just the trick. – daGUY Aug 24 '12 at 01:55
  • 1
    Thank you! For anyone else's reference, if you just want the value pairs, remove the `vars.push(hash[0]);` and reference them by `get['exampleKey']` and so on. – parker_codes Sep 14 '17 at 15:23
  • @ChrisSobolewski if you have space values in the url (such as `%20`) how do you replace these with `" "` before pushing to the vars array? – ckingchris Jun 12 '20 at 19:14
6

Here is the builtin way, for reference: https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams

You can instantiate the current address's parameters as a URL object without importing any libraries as shown here:

let params = (new URL(document.location)).searchParams;

Then you can reference them directly:

let name = params.get('name');

Or you can cycle through them with a loop such as:

for (const [key, value] of params.entries()) {}
Subroot
  • 71
  • 1
  • 5