Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize the form fields and send it to server, jquery?

I have a form in HTML which contains multiple same name fields. For example:

  <form action="" method="post" id="form">
    <div class="itemsection" id="item1">
      <input type="text" name="Price" />
      <input type="text" name="Name" />
      <input type="text" name="Catagory" />
    </div>
    <div class="itemsection" id="item2">
      <input type="text" name="Price" />
      <input type="text" name="Product" />
      <input type="text" name="Catagory" />
    </div>
    <div class="itemsection" id="item3">
      <input type="text" name="Price" />
      <input type="text" name="Product" />
      <input type="text" name="Catagory" />
    </div>
  </form>

Now on the server side (C#), I have an action method and a model class Product:

    //Action method accepts the form on server //It require the Product array 
    public ActionResult SaveItem(Product[] products)
    {
         .....
         ...
    }

    //Model class product
    public Class Product
    {
      public int Id { get; set; }
      public double Price { get; set; }
      public string Name { get; set; }
      public string Catagory { get; set; }
    }

Now my question is: I am submitting the form using jquery $.ajax method. On the server side the action method accepts a Product class array. Now how can I convert the form fields into a Json array (similar to product array). I tried:

   $("#form").serialize();  
           &
   $("#form").serializeArray();

The first generates the name-value pair of all the form fields and the second generates the name-value array of all the form fields. And my requirement is:

  //currently my form contains 3 item section so :
   [
    { "Price" : "value", "Name" : "value", "Catagory" : "value" }, 
    { "Price" : "value", "Name" : "value", "Catagory" : "value" }
    { "Price" : "value", "Name" : "value", "Catagory" : "value" }
   ]

Can anyone tell me how can I can achieve this through JavaScript or JQuery?

like image 595
Tom Rider Avatar asked Nov 13 '22 19:11

Tom Rider


1 Answers

You can use the map method.

var data = $('.itemsection').map(function(){
     return {
        Price: $('input[name="Price"]', this).val(),        
        Product: $('input[name="Product"]', this).val(),
        Category: $('input[name="Category"]', this).val()   
     }
}).get();

http://jsfiddle.net/KRJJ7/

like image 127
undefined Avatar answered Nov 15 '22 08:11

undefined