'Prefill form based on URL parameters javascript
I'm passing name & email through URL parameters from a popup form like this xyz.com?om_email=test%40test.com&om_name=Test
I need these two forms prefilled on xyz.com site
<p>
<input type="text" name="name">
<input type="email" name="email">
</p>
Can anyone please help?
Solution 1:[1]
More context would be nice, but try this:
I used a test URL string to allow the example to work, but on the actual site, replace params variable with the one that is commented, (hint: window.location.search) to extract the parameters from the URL.
There are different ways to do this, but I created an object from the parameter string then looped over the inputs and updated their value by matching the data object key to the input value name attribute.
Note: Be sure to run the JavaScript after the page loads.
var url = "xyz.com?om_email=test%40test.com&om_name=Test";
var params = "om_email=test%40test.com&om_name=Test".split("&");
//use this on the actual site to extract parameters from the url
//var params = window.location.search.slice(1).split("&");
//convert the params to an object
var data = params.reduce((obj, param) => {
var pair = param.split("=");
return { ...obj,
[pair[0].replace("om_", "")]: decodeURIComponent(pair[1])
}
}, {});
//console.log({data});
//insert values by matching input name to data object key
document.querySelectorAll("input").forEach(input => input.value = data[input.name]);
<p>
<input type="text" name="name">
<input type="email" name="email">
</p>
Solution 2:[2]
This is how to autofill a form using HTML5.
<input value="valuehere">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jscrip |
| Solution 2 |
