I am currently trying to prepend an input element to a form for each URL parameter using an object I create based on the URL parameters (since some have more than others).
First, I grab the URL parameters and create the object.
var urlParams = location.search.substring(1);
let parameters = JSON.parse('{"' urlParams.replace(/&/g, '","').replace(/=/g,'":"') '"}', function(key, value) { return key===""?value:decodeURIComponent(value) });
Currently, from a URL: /test-form?utm_source=sig&utm_medium=email&utm_content=comm
This is the expected object: parameters {utm_source: 'sig', utm_medium: 'email', utm_content: 'comm'}
Next, I want to create the input element. The most important attributes in the element are the name and the value field. I have tried a ton of different ways, but I keep running into syntax errors. This is the latest iteration of what I am trying. It has a syntax error. I got this from the for...in documentation on MDN.
for (property in parameters) {
$('<input>', {
type: 'text',
id: `${property}`,
name: `${property}`,
value: `${parameters[property]}`
}).prependTo('form');
I thought that it was because of the property and property values, so I tried to store them in a variable inside of the for...in, but it creates the same issue.
What I expect is:
<input type="text" id="utm_source" name="utm_source" value="sig">
<input type="text" id="utm_medium" name="utm_medium" value="email">
<input type="text" id="utm_content" name="utm_content" value="comm">
CodePudding user response:
You are missing the closing bracket on your for...in.
for (property in parameters) {
$('<input>', {
type: 'text',
id: `${property}`,
name: `${property}`,
value: `${parameters[property]}`
}).prependTo('form');
}