javascript - 在表单提交时格式化 JSON

标签 javascript jquery json forms

(背景)我正在构建一个简单的表单生成器,用户可以在其中创建调查/问卷。一旦用户完成设计将用于创建实际表单的表单,我将创建一个 json 输出。由于它是设计/构建表单的表单构建器用户,因此可以添加复选框或单选框或选择框选项,并可以编辑它们的值和标签。 HTML:

<form class="test-form droppedField checkbox">
<input type="text" name="title" placeholder="Title" class="ctrl-textbox editable"></input>
<input type="text" name="subtitle" placeholder="Sub Title" class="ctrl-textbox editable"></input>
<input type="text" name="name" placeholder="Name/Keyword" class="ctrl-textbox editable">
<input type="hidden" name="type" value="checkbox">
<ul>
    <li>
        <div class="ctrl-checkboxgroup children" name="children">
            <input type="checkbox">
            <input name="label" type="text" value="" placeholder="Option Label.." class="input-small editable">
            <input type="text" value="" name="value" placeholder="Option Value.." class="input-small editable opt-value">
        </div>
        <div class="ctrl-checkboxgroup children" name="children">
            <input type="checkbox">
            <input name="label" type="text" value="" placeholder="Option Label.." class="input-small editable">
            <input type="text" value="" name="value" placeholder="Option Value.." class="input-small editable opt-value">
        </div>
    </li>
</ul>....

我在生成 json 时卡住了。我希望能够通过将复选框选项/单选框/选择框选项组合在一起作为“子项”来获得更清晰的 o/p。示例 json(我认为会有帮助):

[
    {
        "title": "Gender",
        "subtitle": "This is a required question.",
        "name": "gender",
        "children": [
            {
                "label": "Male",
                "value": "male"
            },
            {
                "label": "Female",
                "value": "female"
            },
            {
                "label": "Non traditional",
                "value": "nontraditional"
            }
        ]
    }
]

现在得到了什么:

[
    {
        "title": "Gender",
        "subtitle": "This is a required question.",
        "name": "gender",
        "label":["Male", "Female", "Non traditional"],
        "value":["male", "female", "nontraditional"]
    } 
]

我在做什么:

$('.test-form').each(function () {
   output.push(JSON.stringify($(this).serializeObject()));
});

$.fn.serializeObject = function() {
          var o = {};
          var a = this.serializeArray();
          $.each(a, function() {
              if (o[this.name] !== undefined) {
                  if (!o[this.name].push) {
                      o[this.name] = [o[this.name]];
                  }
                  o[this.name].push(this.value || '');
              } else {
                  o[this.name] = this.value || '';
              }
          });
          return o;
        };

当我将子项插入数组并对其进行迭代时:

obj = [];
$('.children').each(function (i,v) {
    obj.push(obj[v.name] = v.value);
});
console.log(obj);

我得到:

["Male", "male", "Female", "female", "Non traditional", "nontraditional", label: "Non traditional", value: "nontraditional"] 

如果我应该重新构建我的 HTML 或者我是否可以改变 JSON 输出,我很困惑。任何形式的帮助表示赞赏。提前谢谢你。

最佳答案

如果可以将元素的“名称”属性更改为此,则可以修改 serializeObject() 函数来创建所需的 JSON:

<li>
    <div class="ctrl-checkboxgroup children" name="children">
        <input type="checkbox">
        <input name="children[0].label" type="text" value="" placeholder="Option Label.." class="input-small editable">
        <input name="children[0].value" type="text" value="" placeholder="Option Value.." class="input-small editable opt-value">
    </div>
    <div class="ctrl-checkboxgroup children" name="children">
        <input type="checkbox">
        <input name="children[1].label" type="text" value="" placeholder="Option Label.." class="input-small editable">
        <input name="children[1].value" type="text" value="" placeholder="Option Value.." class="input-small editable opt-value">
    </div>
</li>

当然 serializeObject() 函数的逻辑会更复杂,因为它必须用“.”分割名称。并检查方括号。不过这是可能的。

更新:

这是一个jsfiddle显示 serializeObject() 的样子。它支持以下所有输入名称:

  1. xxx
  2. xxx.yyy
  3. xxx[0]
  4. xxx[0].yyy
  5. xxx[0].yyy[0]
  6. xxx[0][0]
  7. xxx[0][0].yyy
  8. xxx[0][0].yyy[0]

关于javascript - 在表单提交时格式化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20621707/

相关文章:

javascript - 如何在 agendaDay View 中正确呈现完整日历

JAVA:如何在嵌套的 JSONString 中查找子字符串的所有匹配项并替换为一些文本

javascript - 使用 json 调用 ArcGIS 服务的 AJAX 无法正常工作

javascript - 有没有办法在Jquery中调用函数 'before document ready'?

javascript - 我想使用此代码链接到另一个页面,并使用从当前页面获取的 id

javascript - $window 错误 '$window not defined' Angular 应用程序中的谷歌分析代码

javascript - 从 JSON 响应创建表

javascript - jQuery:未捕获类型错误:对象#<Object>没有方法 'apply'

javascript - 是否可以在 handlebars.js 模板中使用 JavaScript

javascript - 更新 api 调用 React 中的设置状态