3

Given the following form:

<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>

How can I use query to get the full list of emails and post it as follows to rails:

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

I have the following:

    $.ajax({
        type: 'POST',
        url: '/send_invites',
        data: {
            emails : {
                list : $('.email-form').serialize()
            },
            _method : 'PUT'
        },
        success : function() {
        }
    });
Ozzy
  • 8,244
  • 7
  • 55
  • 95
Rachela Meadows
  • 815
  • 2
  • 12
  • 20

3 Answers3

0

try this:

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));  

or:

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/

Ram
  • 143,282
  • 16
  • 168
  • 197
0

here's a quick way to serialize a form by extending jQuery and adding a serializeObject method.

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

});​
Community
  • 1
  • 1
Joseph
  • 117,725
  • 30
  • 181
  • 234
0

Here is a way to do that

var listval = [];
$("input['name=emails\[\]']").each(function() {
    listval.push($(this).val());
}
Starx
  • 77,474
  • 47
  • 185
  • 261