HTML / Javascript表单如何将表单数据序列化为JSON并在类中显示?

时间:2016-12-31 22:22:27

标签: javascript jquery html json

非常直接。

当用户点击“提交”时,我需要序列化的表单和“debug”类中显示的JSON数据。

如何使用我当前的Javascript进行此操作?

无法使用jQuery。无法编辑HTML。只有纯Javascript。

谢谢!

HTML

<ol class="household"></ol>
    <form>
        <div>
            <label>Age
                <input type="text" name="age">
            </label>
        </div>
        <div>
            <label>Relationship
                <select name="rel">
                    <option value="">---</option>
                    <option value="self">Self</option>
                    <option value="spouse">Spouse</option>
                    <option value="child">Child</option>
                    <option value="parent">Parent</option>
                    <option value="grandparent">Grandparent</option>
                    <option value="other">Other</option>
                </select>
            </label>
        </div>
        <div>
            <label>Smoker?
                <input type="checkbox" name="smoker">
            </label>
        </div>
        <div>
            <button class="add">add</button>
        </div>
        <div>
            <button type="submit">submit</button>
        </div>
    </form>
</div>
<pre class="debug"></pre>

JS

function validate(form) {
        fail = validateAge(form.age.value)
        fail += validateRel(form.rel.value)

        if (fail == "") return true
        else {
            alert(fail);
            return false
        }
    }

    function validateAge(field) {
        if (isNaN(field)) return "No age was entered. \n"
        else if (field < 1 || field > 200)
            return "Age must be greater than 0. \n"
        return ""
    }

    function validateRel(field) {
        if (field == "") return "Please select a relationship \n"
        return ""
    }

    document.querySelector("form").onsubmit = function() {
        return validate(this)
    }

    document.querySelector(".add").onclick = function(event) {
        event.preventDefault();
        createinput()
    }

    count = 0;
    function createinput() {
        field_area = document.querySelector('.household')
        var li = document.createElement("li");
        var p1 = document.createElement("p");
        var p2 = document.createElement("p");
        var p3 = document.createElement("p");
        var x = document.getElementsByName("age")[0].value;
        var y = document.getElementsByName("rel")[0].value;
        var z = document.getElementsByName("smoker")[0].checked;
        if (!z) {
            z = "Non smoker \n";
        } else {
            z = "Smoker \n";
        }
        p1.innerHTML = x;
        p2.innerHTML = y;
        p3.innerHTML = z;
        li.appendChild(p1);
        li.appendChild(p2);
        li.appendChild(p3);
        field_area.appendChild(li);
        //removal link
        var removalLink = document.createElement('a');
        removalLink.onclick = function() {
            this.parentNode.parentNode.removeChild(this.parentNode)
        }
        var removalText = document.createTextNode('Remove Field');
        removalLink.appendChild(removalText);
        li.appendChild(removalLink);
        count++
    }

    // serialize form
    var data = {};
    var inputs = [].slice.call(e.target.querySelector('form'));
    inputs.forEach(input => {
        data[input.name] = input.value;
    });

2 个答案:

答案 0 :(得分:3)

最短的解决方案(纯javascript):

var form = document.querySelector('form');
var data = new FormData(form);

docs:https://developer.mozilla.org/en-US/docs/Web/API/FormData

答案 1 :(得分:2)

遍历表单,抓取各个元素并为每个元素创建新对象,然后设置每个对象的属性并推送到最终数组将很容易地解决您的问题。

然后,您只需使用querySelectorAll匹配.debug并使用JSON.stringify()将数组转换为字符串,然后innerText设置内容。

示例:

function go() {
  var debug_class = document.querySelectorAll(".debug");
  for (var i = 0; i < debug_class.length; i++) {
    var element = debug_class[i];
    element.innerText = JSON.stringify(serializeArray(document.querySelector("form")));
  }

}

function serializeArray(form) {
  var field, l, s = [];
  if (typeof form == 'object' && form.nodeName == "FORM") {
    var len = form.elements.length;
    for (i = 0; i < len; i++) {
      field = form.elements[i];
      if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
        if (field.type == 'select-multiple') {
          l = form.elements[i].options.length;
          for (j = 0; j < l; j++) {
            if (field.options[j].selected)
              s[s.length] = {
                name: field.name,
                value: field.options[j].value
              };
          }
        } else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
          s[s.length] = {
            name: field.name,
            value: field.value
          };
        }
      }
    }
  }
  return s;
}
<form id="blah">
  <input type="text" name="input1" value="a"></input>
  <input type="text" name="input2" value="b"></input>
  <input type="text" name="input3" value="c"></input>
  <input type="text" name="input4" value="d"></input>

</form>
<button onclick="go()">Serialize!</button>

<div class="debug"></div>

修改

在您的特定情况下,在包含上述代码之后,您必须在某个时刻调用go()来生成序列化数据。

点击add

后,如何操作
 document.querySelector(".add").onclick = function(event) {
        go();   // display in .debug
        event.preventDefault();
        createinput()
    }

FULL SNIPPET

function go() {
  var debug_class = document.querySelectorAll(".debug");
  for (var i = 0; i < debug_class.length; i++) {
    var element = debug_class[i];
    element.innerText = JSON.stringify(serializeArray(document.querySelector("form")));
  }

}

function serializeArray(form) {
  var field, l, s = [];
  if (typeof form == 'object' && form.nodeName == "FORM") {
    var len = form.elements.length;
    for (i = 0; i < len; i++) {
      field = form.elements[i];
      if (field.name && !field.disabled && field.type != 'file' && field.type != 'reset' && field.type != 'submit' && field.type != 'button') {
        if (field.type == 'select-multiple') {
          l = form.elements[i].options.length;
          for (j = 0; j < l; j++) {
            if (field.options[j].selected)
              s[s.length] = {
                name: field.name,
                value: field.options[j].value
              };
          }
        } else if ((field.type != 'checkbox' && field.type != 'radio') || field.checked) {
          s[s.length] = {
            name: field.name,
            value: field.value
          };
        }
      }
    }
  }
  return s;
}


function validate(form) {
  fail = validateAge(form.age.value)
  fail += validateRel(form.rel.value)

  if (fail == "") return true
  else {
    alert(fail);
    return false
  }
  go();
}

function validateAge(field) {
  if (isNaN(field)) return "No age was entered. \n"
  else if (field < 1 || field > 200)
    return "Age must be greater than 0. \n"
  return ""
}

function validateRel(field) {
  if (field == "") return "Please select a relationship \n"
  return ""
}

document.querySelector("form").onsubmit = function() {
  return validate(this)
}

document.querySelector(".add").onclick = function(event) {
  go();
  event.preventDefault();
  createinput()
}

count = 0;

function createinput() {
  field_area = document.querySelector('.household')
  var li = document.createElement("li");
  var p1 = document.createElement("p");
  var p2 = document.createElement("p");
  var p3 = document.createElement("p");
  var x = document.getElementsByName("age")[0].value;
  var y = document.getElementsByName("rel")[0].value;
  var z = document.getElementsByName("smoker")[0].checked;
  if (!z) {
    z = "Non smoker \n";
  } else {
    z = "Smoker \n";
  }
  p1.innerHTML = x;
  p2.innerHTML = y;
  p3.innerHTML = z;
  li.appendChild(p1);
  li.appendChild(p2);
  li.appendChild(p3);
  field_area.appendChild(li);
  //removal link
  var removalLink = document.createElement('a');
  removalLink.onclick = function() {
    this.parentNode.parentNode.removeChild(this.parentNode)
  }
  var removalText = document.createTextNode('Remove Field');
  removalLink.appendChild(removalText);
  li.appendChild(removalLink);
  count++
}

// serialize form

var data = {};
var inputs = [].slice.call(e.target.querySelector('form'));
inputs.forEach(input => {
  data[input.name] = input.value;
});
<ol class="household"></ol>
<form>
  <div>
    <label>Age
      <input type="text" name="age">
    </label>
  </div>
  <div>
    <label>Relationship
      <select name="rel">
        <option value="">---</option>
        <option value="self">Self</option>
        <option value="spouse">Spouse</option>
        <option value="child">Child</option>
        <option value="parent">Parent</option>
        <option value="grandparent">Grandparent</option>
        <option value="other">Other</option>
      </select>
    </label>
  </div>

  <div>

    <label>Smoker?
      <input type="checkbox" name="smoker">
    </label>
  </div>

  <div>
    <button class="add">add</button>
  </div>
  <div>
    <button type="submit">submit</button>
  </div>
</form>
</div>
<pre class="debug"></pre>