问题描述
<form>
<div data-id="x">
<label>field 1</label>
<input name="field1" type="text" value="Foo" />
<label>field 2</label>
<input name="field2" type="number" value="5" />
</div>
<div data-id="y">
<label>field 1</label>
<input name="field1" type="text" value="Foo" />
<label>field 2</label>
<input name="field2" type="number" value="5" />
</div>
...other 100 inputs...
</form>
我正在寻找这样的 javascript 脚本:
var theElement = document.querySelector('[data-id="x"]');
var myObject = theElement.toObject();
并且对象必须看起来像
{"field1":"Foo","field2":5}
我无法使用 FormData
策略,因为我需要来自一个非常大的表单的非常小的数据集,但它就像一个“部分 FormData”。
我在问是否存在一种标准方法来转换对象中 HTMLElement 的内容,例如 FormData。
PS:如有必要,我也可以使用数据属性
解决方法
实际上没有标准的快速方法来完成这项任务。
解决方案是迭代输入和选择:
<script>
let myObj = {};
let element = document.querySelector('[data-id="x"]');
element.querySelectorAll('input').forEach(el=> {
// check the type
// the property is : el.name
// the value must be : el.value for text/number/email...
// the value for the type="checkbox" is according to checked attribute
});
element.querySelectorAll('select').forEach(sel=> {
// if multiple choise => create an array of selected options
// if single => check the selected option's value
});
</script>
这是我使用的代码(简化)