如何根据表单的文本输入准备值列表?

时间:2012-04-20 22:28:15

标签: javascript jquery ajax arrays forms

考虑以下形式:

<form class="email-form" action="" method="PUT" data-remote="true" data-method="put">
  <ul>
    <li>
      <label for="sEmail1">
        <input type="text" id="sEmail1" name="emails[]" value="d@google.com"
               placeholder="">
      </label>
    </li>
    <li>
      <label for="sEmail2">
        <input type="text" id="sEmail2" name="emails[]" value="d2@google.com"
               placeholder="">
      </label>
    </li>
    <li>
      <label for="sEmail3">
        <input type="text" id="sEmail3" name="emails[]" value="d3@google.com"
               placeholder="">
      </label>
    </li>
  </ul>
  <button type="submit">Continue</button>
</form>

如何使用查询获取完整的电子邮件列表,并将其发布如下到rails:

Parameters: {"emails"=>{"list"=>["d@google.com", "d2@google.com","d2@google.com"]}}

我有以下内容:

    $.ajax({
        type: 'POST',
        url: '/send_invites',
        data: {
            emails : {
                list : $('.email-form').serialize()
            },
            _method : 'PUT'
        },
        success : function() {
        }
    });

3 个答案:

答案 0 :(得分:0)

试试这个:

emails = new Object();
emails.list = [];
i = 0;

$("input[name^='email']").each(function(){
   if(i < 3) {
    emails.list[i] = $(this).val();
    i++
  }

})

alert(JSON.stringify(emails));  

或:

parameters = new Object();
parameters.emails = new Object()
parameters.emails.list= [];
i = 0;

$("input[name^='email']").each(function(){
   if(i < 3) {
    parameters.emails.list[i] = $(this).val();
    i++
  }

})

alert(JSON.stringify(parameters));   

http://jsfiddle.net/jgjpD/1/

答案 1 :(得分:0)

这是quick way to serialize a form,它扩展了jQuery并添加了serializeObject方法。

$(function() {

    //form to object
    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            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 || '';
            }
        });
        return o;
    };

    //test it out
    $('form').on('submit', function() {
        var serialized = $(this).serializeObject();

        console.log(serialized);
        console.log(JSON.stringify(serialized));

        return false;
    });

});​

答案 2 :(得分:0)

这是一种方法

var listval = [];
$("input['name=emails\[\]']").each(function() {
    listval.push($(this).val());
}