I'm passing name & email through URL parameters from a popup form like this [email protected]&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?
CodePudding user response:
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 = "[email protected]&om_name=Test";
var params = "[email protected]&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>
CodePudding user response:
This is how to autofill a form using HTML5.
<input value="valuehere">