首页 > 解决方案 > 从 JavaScript 对象属性创建表单

问题描述

我有一个运行 JSON 数据的 Web 应用程序,我提取了一部分并最终得到一个具有一些属性的对象:

var formProps = {
    Name: "Some Name value",
    Age: "18", 
    AnotherField: "Some other value"
}

我正在尝试找到一种从属性创建表单的有效方法。

<div class="formitem">
<label>Some Name Value</label>
<input type="text" name="AnotherField" value="Some other value"/>
</div>

我无法决定是否应该生成 HTML 并将其转储到页面上已经存在的另一个 div 中,或者是否应该通过 JS 创建新的 DOM 元素...

标签: javascriptjson

解决方案


如果你希望它是动态的,你别无选择,只能从 JavaScript 创建新的 DOM 元素。

一种方法是使用 HTML 模板定义表单项结构,这将允许您在 HTML 中定义大部分结构。然后,您可以为对象中的每个属性在页面中克隆、自定义和附加此模板。

const formProps = {
  Name: "Some Name value",
  Age: "18", 
  AnotherField: "Some other value"
}

function createField(prop, value) {
  const tpl = document.querySelector('#formitem-tpl');
  const clone = document.importNode(tpl.content, true);
  clone.querySelector('label').innerHTML = prop;
  const input = clone.querySelector('input');
  input.value = value;
  input.name = prop;
  return clone;
}

const form = document.querySelector('#form');

for (let [key, val] of Object.entries(formProps)) {
  form.appendChild(createField(key, val));
}
<template id="formitem-tpl">
  <div class="formitem">
    <label></label>
    <input type="text" name="" value=""/>
  </div>
</template>

<div id="form">
</div>


推荐阅读