【发布时间】:2020-10-02 06:59:44
【问题描述】:
我有一个由一系列单元组成的 HTML 表单,如下所示:
<input name="categoryColor[]" />
<input name="categoryName[]" />
使用这个jQuery code,我可以捕获这些数据并将其返回到这样的对象中:
{categoryColor: [array of values],
categoryName: [array of values]}
下面是实际代码示例:
const getFormDataFromElem = function($elem, options) {
options = options || {};
const vis = options.onlyVisible ? ":visible" : "";
const formInputs = $elem.find(`:input${vis}, [contenteditable=true]${vis}`);
const data = {};
formInputs.each(function() {
const $this = $(this)
const type = $this.attr('type');
const val = type === "checkbox" ? (this.checked ? "1" : "0") :
($this.is('[contenteditable=true]') ? $this.text() : this.value);
const name0 = $this.attr('name');
const doArray = name0 && name0.slice(-2) === "[]";
const name = doArray ? name0.slice(0, -2) : name0;
if (!name || (!options.saveEmpty && !doArray && val === "")) {
return;
}
if (doArray) {
if (data.hasOwnProperty(name)) {
data[name].push(val);
return
}
data[name] = [val];
return;
}
data[name] = val;
});
return data;
};
const data = getFormDataFromElem($('.input'));
$('.output').text(JSON.stringify(data, null, 2));
.output {
font-family: monospace;
white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Input</h2>
<div class="input">
<input name="categoryName[]" value="phase1"/>
<input name="categoryColor[]" value="red"/>
<input name="categoryName[]" value="phase2"/>
<input name="categoryColor[]" value="green"/>
<input name="categoryName[]" value="phase3"/>
<input name="categoryColor[]" value="blue"/>
</div>
<h2>Output</h2>
<div class="output"></div>
但我希望能够像这样编写 HTML 表单单元
<input name="categories[].color" />
<input name="categories[].name" />
因为我真的需要这种形式的数据:
{categories: [array of objects],
}
对象的格式为{name: '<name of category>', color: '<color string>'}。
如何重写我的通用表单捕获例程以生成任意数组和对象的值?
【问题讨论】:
-
name="categories[_COUNTER_][color]" -
@GrumpyCrouton,谢谢!
_COUNTER_是文字还是代表我必须手动输入的序数?我认为color是文字? -
_COUNTER_需要用一个计数器替换,可能是一个从0开始的for循环到有多少输入。color是一个文字字符串。 -
@GrumpyCrouton,感谢您的澄清。你是说我在这里的 JS 代码会自动生成我描述的对象,或者是否有一些我应该使用的内置 jQuery 方法?我无法看到我拥有的代码是如何实现的。
-
请参阅此解决方案,了解在名称 stackoverflow.com/a/39248551/1175966 中使用多个
[][]的表单到对象
标签: javascript html jquery forms