我有一个带有许多输入字段的表单。

当我用jQuery捕获提交表单事件时,是否有可能在一个关联数组中获得该表单的所有输入字段?


当前回答

$('#myForm').submit(function() {
    // get all the inputs into an array.
    var $inputs = $('#myForm :input');

    // not sure if you wanted this, but I thought I'd add it.
    // get an associative array of just the values.
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

});

感谢来自Simon_Weaver的提示,这里有另一种方法,你可以使用serializeArray:

var values = {};
$.each($('#myForm').serializeArray(), function(i, field) {
    values[field.name] = field.value;
});

注意,这个代码段在<select multiple>元素时将失败。

在jQuery 1.3版本中,新的HTML 5表单输入不能使用serializeArray。这适用于版本1.4+

其他回答

在这个问题上有点晚了,但这个更简单:

$('#myForm').submit(function() {
    // Get all the forms elements and their values in one step
    var values = $(this).serialize();

});
$('#myForm').bind('submit', function () {
  var elements = this.elements;
});

elements变量将包含表单中的所有输入、选择、文本区域和字段集。

似乎很奇怪,没有人赞成或提出一个简洁的解决方案来获得列表数据。几乎没有任何形式是一维对象。

当然,这种解决方案的缺点是必须在[0]索引处访问单例对象。但在我看来,这比使用12行映射解决方案要好得多。

var formData = $('#formId').serializeArray().reduce(function (obj, item) {
    if (obj[item.name] == null) {
        obj[item.name] = [];
    } 
    obj[item.name].push(item.value);
    return obj;
}, {});

我使用这段代码没有每个循环:

$('.subscribe-form').submit(function(e){
    var arr=$(this).serializeArray();
    var values={};
    for(i in arr){values[arr[i]['name']]=arr[i]['value']}
    console.log(values);
    return false;
});

这里有另一种解决方案,通过这种方式,您可以获取关于表单的所有数据,并在服务器端调用或其他地方使用它。

$('.form').on('submit', function( e )){ 
   var form = $( this ), // this will resolve to the form submitted
       action = form.attr( 'action' ),
         type = form.attr( 'method' ),
         data = {};

     // Make sure you use the 'name' field on the inputs you want to grab. 
   form.find( '[name]' ).each( function( i , v ){
      var input = $( this ), // resolves to current input element.
          name = input.attr( 'name' ),
          value = input.val();
      data[name] = value;
   });

  // Code which makes use of 'data'.

 e.preventDefault();
}

然后你可以使用ajax调用:

function sendRequest(action, type, data) {
       $.ajax({
            url: action,
           type: type,
           data: data
       })
       .done(function( returnedHtml ) {
           $( "#responseDiv" ).append( returnedHtml );
       })
       .fail(function() {
           $( "#responseDiv" ).append( "This failed" );
       });
}

希望这对你们任何人都有用:)