简体   繁体   English

将HTML表单数组序列化为Javascript数组

[英]Serializing HTML form array to Javascript array

I have a form containing a list of text fields 我有一个包含文本字段列表的表单

<input type="text" name="list[]" value="">
<input type="text" name="list[]" value="">

I'm running some custom jQuery to validate the input and do a few other things, before displaying a JSON chunk to the user. 在向用户显示JSON块之前,我正在运行一些自定义jQuery来验证输入并做其他一些事情。 What I want to achieve is these elements should become a standard javascript array a la: 我要实现的是这些元素应成为标准的JavaScript数组:

{"list":["something","something else"]}

Is there a simple call I can make on the specific element to pull it in as an array, something like this? 我可以对特定元素进行简单的调用以将其作为数组拉入吗?

var jsonVars = {};
jsonVars['list'] = $("input[name=list]").getArray();

With the structure you have and assuming you want to get the values you could do: 使用您拥有的结构并假设您想要获取值,您可以执行以下操作:

var jsonVars = {};
jsonVars['list'] = $('input[name="list[]"]').map(function(){return this.value;}).get();

You can use $('input[name="list[]"]').serializeArray() but will return in a different format as array of objects (with name and value). 您可以使用$('input[name="list[]"]').serializeArray()但是将以不同的格式作为对象数组(带有名称和值)返回。

There's jQuery's serialize function. 有jQuery的序列化功能。 This topic is similar to yours and might give you some more advanced insight. 该主题与您的主题相似,可能会给您一些更高级的见解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM