Home > Mobile >  Insert Form data into empty form
Insert Form data into empty form

Time:09-28

when a HTML form is submitted/sent to a server via POST, the form data is sent via a "form-string" using the syntax key1=value1&key2=value2&... and the server can process this data.

Is there an native way using Javascript and HTML to do the following: The empty HTML form is given, and form-string with the syntax key1=value1&key2=value2 (the same syntax like when form data would be sent via POST). Now "fill" the empty HTML form with the data from the form-string.

I think its not difficult to implement this looping over the values in the form string and insert them using DOM-operations but maybe theres a nicer, native way to do this? (like, a one-liner)

CodePudding user response:

Lets say you have the following inputs:

<input type="text" id="fname" />
<input type="text" id="lname" />

You can set the value prop for each of these inputs to populate data into their inputs from your given format:

const data = 'fname=john&lname=doe';
data.split('&').forEach((keyValuePair) => {
  document.getElementById(keyValuePair.split('=')[0]).value = keyValuePair.split('=')[0];
})

This is rudimentary and exclusive to your use-case, so I would recommend looking at the URLSearchParams documentation to build a more robust solution.

CodePudding user response:

If for some reason you can't set the field's value initially in the HTML:

<input type="text" name="key1" value="Initial value 1" /> 

and, again for some reason, you absolutely have to resort to doing it via JavaScript from an initial String value, then here's a short way:

const string = 'key1=value1&key2=value2&key3=value3' // your initial string

//Split, interate, and set the field's value (if the field with name="key..." exists)
string.split('&').forEach(pair => {
  let [key, val] = pair.split('=')
  let field = document.querySelector(`[name=${key}]`)
  if (field) {
    field.value = val
  }
})

  • Related