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

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


当前回答

对于语义ui/formantic ui,有一个内置的行为get值:

const fields = $("#myForm.ui.form").form('get values');
const jsonStr = JSON.stringify(fields);

看见https://fomantic-ui.com/behaviors/form.html#/settings

get-values(标识符)返回与标识符数组匹配的元素值的对象。如果未通过IDS,将返回所有字段

其他回答

所有这些答案对我来说似乎都太过头了。为了简单起见,有些话要说。只要您的所有表单输入都设置了name属性,这应该只适用于jimdandy。

$('form.myform').submit(函数(){var$this=$(this),viewArr=$this.serializeArray(),视图={};for(viewArr中的var i){view[viewArr[i].name]=viewArr[i].value;}//在这里使用视图对象(例如JSON.stringify?)});

const formData = new FormData(form);

let formDataJSON = {};

for (const [key, value] of formData.entries()) {

    formDataJSON[key] = value;
}

如果使用Undercore.js,可以使用相对简洁的:

_.object(_.map($('#myform').serializeArray(), _.values))

这种解决方案更好。这里的一些更流行的选项在未选中复选框时不会更正句柄复选框。

getData: function(element){
//@todo may need additional logic for radio buttons
var select = $(element).find('select');
var input = $(element).find('input');
var inputs = $.merge(select,input);
var data = {};
//console.log(input,'input');
$.each(inputs,function(){
  if($(this).attr('type') != undefined){
    switch($(this).attr('type')){
     case 'checkbox':
        data[$(this).attr('name')] = ( ($(this).attr('checked') == 'checked') ? $(this).val():0 );
        break;
      default:
        data[$(this).attr('name')] = $(this).val();
        break;
    }
  } 
  else {
    data[$(this).attr('name')] = $(this).val();
  }
})
  return data;
}

这是对Tobias Cohen函数的改进,该函数在多维数组中运行良好:

http://jsfiddle.net/BNnwF/2/

然而,这不是一个jQuery插件,但如果您想这样使用它,只需几秒钟就可以将它变成一个:只需替换函数声明包装器:

function serializeFormObject(form)
{
    ...
}

具有:

$.fn.serializeFormObject = function()
{
    var form = this;
    ...
};

我想这与梅斯克的解决方案相似,因为它做了相同的事情,但我认为这有点干净和简单。我还将macek的测试用例输入添加到小提琴中,并添加了一些额外的输入。到目前为止,这对我来说很好。

function serializeFormObject(form)
{
    function trim(str)
    {
        return str.replace(/^\s+|\s+$/g,"");
    }

    var o = {};
    var a = $(form).serializeArray();
    $.each(a, function() {
        var nameParts = this.name.split('[');
        if (nameParts.length == 1) {
            // New value is not an array - so we simply add the new
            // value to the result object
            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 || '';
            }
        }
        else {
            // New value is an array - we need to merge it into the
            // existing result object
            $.each(nameParts, function (index) {
                nameParts[index] = this.replace(/\]$/, '');
            });

            // This $.each merges the new value in, part by part
            var arrItem = this;
            var temp = o;
            $.each(nameParts, function (index) {
                var next;
                var nextNamePart;
                if (index >= nameParts.length - 1)
                    next = arrItem.value || '';
                else {
                    nextNamePart = nameParts[index + 1];
                    if (trim(this) != '' && temp[this] !== undefined)
                        next = temp[this];
                    else {
                        if (trim(nextNamePart) == '')
                            next = [];
                        else
                            next = {};
                    }
                }

                if (trim(this) == '') {
                    temp.push(next);
                } else
                    temp[this] = next;

                temp = next;
            });
        }
    });
    return o;
}