1

We want to set various inputs to the values contained in a str inputValueStr obtained like so:

  const form = document.querySelector('#theForm');
  var object = Object.values(form).reduce((obj, field) => { obj[field.name] = field.value; return obj }, {});
  delete object[""];
  const inputValuesStr =  new URLSearchParams(object).toString()

The string looks like "foo=&bar=123&baz=examplestr&whatever=". What's a good way to set the #theForm's inputs to the values from the string (ie. make inputs of bar = 123, baz = "examplestr", and other inputs null)?

We're unsure if we're missing something as we don't know what to search for so apologies if this is a stupid question. If so please feel free to redirect us to another thread.

1 Answer 1

1

First you have to get all the variables in the URL:

const urlParams = new URLSearchParams(window.location.search);

Then, you can iterate over every parameter and set the form's input to its value:

urlParams.forEach((val, key) => {
   const inputEl = document.querySelector('#theForm [name="'+key+'"]');
   if(inputEl) 
       inputEl.value = val;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.