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

当我用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();

});

我也遇到过同样的问题,只是用了不同的方法。

var arr = new Array();
$(':input').each(function() {
 arr.push($(this).val());
});
arr;

它返回所有输入字段的值。您可以将$(':input')更改为更具体。

jQuery的serializeArray不包括禁用字段,所以如果你也需要这些,试试:

var data = {};
$('form.my-form').find('input, textarea, select').each(function(i, field) {
    data[field.name] = field.value;
});

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

$('.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" );
       });
}

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

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

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