April 20, 2012

How to prepare a list of values based on a form's text inputs?

Question by Rachela Meadows

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

Answer by Starx

Here is a way to do that

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!