Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill form with JSON?

I get ajax response as JSON and need to fill a form with it. How to do that in jQuery or something else ? Is something better than using $(json).each() ?

JSON:

{ 
  "id" : 12,
  "name": "Jack",
  "description": "Description"
}

Form to fill

<form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form>
like image 667
marioosh Avatar asked Aug 04 '11 07:08

marioosh


1 Answers

Came here searching for a solution that didn't involve jQuery or a brunch of DOM scaning, but didn't find one... so here is my vanilla js solution brought to you other guys that probably ditched jQuery long ago.

const data = { 
  "id" : 12,
  "name": "Jack",
  "description": "Description",
  "nonExisting": "works too"
}

const { elements } = document.querySelector('form')

for (const [ key, value ] of Object.entries(data) ) {
  const field = elements.namedItem(key)
  field && (field.value = value)
}
<form>
  <input type="text" name="id"/>
  <input type="text" name="name"/>
  <input type="text" name="description"/>
</form>
like image 70
Endless Avatar answered Sep 21 '22 06:09

Endless