如何将表单的所有元素转换为JavaScript对象?

我希望有某种方法从表单自动构建JavaScript对象,而不必遍历每个元素。我不希望使用$('#formid').serialize();返回的字符串;,我也不希望$('#formid').serializeArray()返回映射;


当前回答

此代码转换并保存输入类型,而不是全部转换为字符串:

jQuery.fn.serializeForm = function () {
    var form = this.get(0);
    var i = [];
    var ret = {};
    for (i = form.elements.length - 1; i >= 0; i = i - 1) {
        if (form.elements[i].name === "") {
            continue;
        }
        var name = form.elements[i].name;
        switch (form.elements[i].nodeName) {
            case 'INPUT':
                switch (form.elements[i].type) {
                    case 'text':
                    case 'tel':
                    case 'email':
                    case 'hidden':
                    case 'password':
                        ret[name] = encodeURIComponent(form.elements[i].value);
                        break;
                    case 'checkbox':
                    case 'radio':
                        ret[name] = form.elements[i].checked;
                        break;
                    case 'number':
                        ret[name] = parseFloat(form.elements[i].value);
                        break;
                }
                break;
            case 'SELECT':
            case 'TEXTAREA':
                ret[name] = encodeURIComponent(form.elements[i].value);
                break;
        }
    }
    return ret;
};

例如,这是输出:

Day: 13
Key: ""
Month: 5
OnlyPayed: true
SearchMode: "0"
Year: 2021

而不是

Day: "13"
Key: ""
Month: "5"
OnlyPayed: "true"
SearchMode: "0"
Year: "2021"

其他回答

像boss一样将表单转换为JSON


目前的来源是GitHub和Bower。

$bower安装jquery序列化对象


以下代码现已弃用。

以下代码可以处理所有类型的输入名称;按照你的预期处理它们。

例如:

<!-- All of these will work! -->
<input name="honey[badger]" value="a">
<input name="wombat[]" value="b">
<input name="hello[panda][]" value="c">
<input name="animals[0][name]" value="d">
<input name="animals[0][breed]" value="e">
<input name="crazy[1][][wonky]" value="f">
<input name="dream[as][vividly][as][you][can]" value="g">
// Output
{
  "honey":{
    "badger":"a"
  },
  "wombat":["b"],
  "hello":{
    "panda":["c"]
  },
  "animals":[
    {
      "name":"d",
      "breed":"e"
    }
  ],
  "crazy":[
    null,
    [
      {"wonky":"f"}
    ]
  ],
  "dream":{
    "as":{
      "vividly":{
        "as":{
          "you":{
            "can":"g"
          }
        }
      }
    }
  }
}

用法

$('#my-form').serializeObject();

魔法(JavaScript)

(function($){
    $.fn.serializeObject = function(){

        var self = this,
            json = {},
            push_counters = {},
            patterns = {
                "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
                "key":      /[a-zA-Z0-9_]+|(?=\[\])/g,
                "push":     /^$/,
                "fixed":    /^\d+$/,
                "named":    /^[a-zA-Z0-9_]+$/
            };


        this.build = function(base, key, value){
            base[key] = value;
            return base;
        };

        this.push_counter = function(key){
            if(push_counters[key] === undefined){
                push_counters[key] = 0;
            }
            return push_counters[key]++;
        };

        $.each($(this).serializeArray(), function(){

            // Skip invalid keys
            if(!patterns.validate.test(this.name)){
                return;
            }

            var k,
                keys = this.name.match(patterns.key),
                merge = this.value,
                reverse_key = this.name;

            while((k = keys.pop()) !== undefined){

                // Adjust reverse_key
                reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

                // Push
                if(k.match(patterns.push)){
                    merge = self.build([], self.push_counter(reverse_key), merge);
                }

                // Fixed
                else if(k.match(patterns.fixed)){
                    merge = self.build([], k, merge);
                }

                // Named
                else if(k.match(patterns.named)){
                    merge = self.build({}, k, merge);
                }
            }

            json = $.extend(true, json, merge);
        });

        return json;
    };
})(jQuery);

如果您想将表单转换为javascript对象,那么最简单的解决方案(此时)是使用jQuery的each和serializArray函数方法。

$.fn.serializeObject = function() {

  var form = {};
  $.each($(this).serializeArray(), function (i, field) {
    form[field.name] = field.value || "";
  });

  return form;
};

GitHub上托管的插件:https://github.com/tfmontague/form-object/blob/master/README.md

可与Bower一起安装:船首装置git://github.com/tfmontague/form-object.git

Tobias Cohen解决方案的固定版本。此函数正确处理0和“”等错误值。

jQuery.fn.serializeObject = function() {
  var arrayData, objectData;
  arrayData = this.serializeArray();
  objectData = {};

  $.each(arrayData, function() {
    var value;

    if (this.value != null) {
      value = this.value;
    } else {
      value = '';
    }

    if (objectData[this.name] != null) {
      if (!objectData[this.name].push) {
        objectData[this.name] = [objectData[this.name]];
      }

      objectData[this.name].push(value);
    } else {
      objectData[this.name] = value;
    }
  });

  return objectData;
};

以及一个CoffeeScript版本,方便您编写代码:

jQuery.fn.serializeObject = ->
  arrayData = @serializeArray()
  objectData = {}

  $.each arrayData, ->
    if @value?
      value = @value
    else
      value = ''

    if objectData[@name]?
      unless objectData[@name].push
        objectData[@name] = [objectData[@name]]

      objectData[@name].push value
    else
      objectData[@name] = value

  return objectData

所以我使用了公认的答案,发现了一个主要缺陷。它不支持以下输入数组:

<input type="checkbox" name="array[]" value="1"/>
<input type="checkbox" name="array[]" value="2"/>
<input type="checkbox" name="array[]" value="3"/>

这一小改动应该可以解决以下问题:

function objectifyForm(inp){
    var rObject = {};
    for (var i = 0; i < inp.length; i++){
        if(inp[i]['name'].substr(inp[i]['name'].length - 2) == "[]"){
            var tmp = inp[i]['name'].substr(0, inp[i]['name'].length-2);
            if(Array.isArray(rObject[tmp])){
                rObject[tmp].push(inp[i]['value']);
            } else{
                rObject[tmp] = [];
                rObject[tmp].push(inp[i]['value']);
            }
        } else{
            rObject[inp[i]['name']] = inp[i]['value'];
        }
    }
    return rObject;
}

记住将$(this).serializeArray()的输出传递给它;否则它不会起作用。

这会把一切都考虑在内

函数formToObject(表单){let data=新FormData(表单);let queryString=新URLSearchParams(data).toString();var obj={};var params=queryString.split(“&”);对于(var i=0;i<params.length;i++){var param=params[i].split(“=”);var key=param[0].replace(“[]”,“”);var key=密钥.替换(“%5B%5 D”,“”);var值=参数[1];if(obj[key]==未定义){obj[key]=值;}else if(数组的obj[key]实例){obj[key].push(值);}其他{obj[key]=[obj[key],值];}}控制台日志(obj)返回obj;}<!DOCTYPE html><html><head><title>表单示例</title></head><body style=“height:800px;溢出:滚动”><form id=“test”onchange=“formToObject(this)”><div><h3>水果</h3><input type=“checkbox”name=“fruit”value=“apple”id=“apple“><label for=“apple”>Apfel</label><input-type=“checkbox”name=“fruit”value=“banana”id=“banana“><label for=“banana”>Banane</label><input type=“checkbox”name=“fruit”value=“cherry”id=“cherr”><label for=“cherry”>Kirsche</label><input type=“checkbox”name=“fruit”value=“葡萄”id=“葡萄”><label for=“葡萄”>Traube</label><input type=“checkbox”name=“fruit”value=“pear”id=“pear“><label for=“pear”>Birne</label></div><div><h3>多个选项</h3><select multiple name=“manyOptions[]”><option value=“选项1”>选项1</option><option value=“option 2”>选项2</option><option value=“选项3”>选项3</option></选择></div><div><h3>检查选项</h3><input type=“radio”name=“onceOption”value=“Option 1”>选项1<br><input type=“radio”name=“onceOption”value=“Option 2”>选项2<br><input type=“radio”name=“onceOption”value=“Option 3”>选项3<br></div></form></body></html>