使用相同的UI字段生成JSON

时间:2018-05-23 21:45:31

标签: javascript angularjs json

我有一个这样的表单:https://jsfiddle.net/6vocc2yn/返回一个类似

的json
    {
  "List": [
    {
      "Id": 10,
      "Name": "SDB_SOLOCHALLENGE_CHALLENGE_DESC_10",
      "email": "abc.abc@xyz.com",
      "message": "SDB_SOLOCHALLENGE_CHALLENGE_BACKGROUND_IMAGE_10",
      "someOtherList": [
        {
          "a": 10,
          "b": 14
        }
      ],
      "opponentFighterItemDefinitionId": 4294967295,
      "title": "abc"
    }
  ]
}

我想要一个Add按钮,它只会重置当前字段,但保存信息并附加用户下次输入的信息。

例如:

{
      "List": [
        {
          "Id": 10,
          "Name": "CHALLENGE_DESC_10",
          "email": "abc.abc@xyz.com",
          "message": "BACKGROUND_IMAGE_10",
          "someOtherList": [
            {
              "a": 10,
              "b": 14
            }
          ],
          "oppId": 111,
          "title": "abc"
        },

       {
      "Id": 11,
      "Name": "CHALLENGE_DESC_11",
      "email": "abc.abc@xyz.com",
      "message": "CHALLENGE_BACKGROUND_IMAGE_11",
      "someOtherList": [
        {
          "a": 11,
          "b": 15
        }
      ],
      "oppId": 222,
      "title": "abc"
    }
      ]
    }

如何与.push有效合并?

1 个答案:

答案 0 :(得分:0)

var dataObject = {
    List: []
};

document.getElementById('add').addEventListener('click', function(e) {
    e.preventDefault();
    var formData = {
    name: document.getElementById("name").value,
    mail: document.getElementById("mail").value,
    msg: document.getElementById("msg").value
  };

  dataObject.List.push(formData);
  console.log(dataObject);

  // formId is the id of the form, "<form id="formId"..."
  document.getElementById("formId").reset();
});