mattb
mattb

Reputation: 25

jQuery serialize multiple forms and send as JSON

I have multiple forms on a page where each form will add individual item to the database. There's also an 'Add all' button that'll send all products data. See basic html below:

<button type="submit">All all products</a>

<form>
<input type="hidden" name="Product" value="ProductA" />
<input type="checkbox" name="optionAll" value="Option All" /> Option All 
<input type="checkbox" name="option" value="Option 1" checked="checked" /> Option 1 
<input type="checkbox" name="option" value="Option 2" /> Option 2
<button type="submit">Add this product"</button> 
</form>

<form>
<input type="hidden" name="Product" value="ProductB" />
<input type="checkbox" name="optionAll" value="Option All" /> Option All 
<input type="checkbox" name="option" value="Option 1" checked="checked" /> Option 1 
<input type="checkbox" name="option" value="Option 2" checked="checked" /> Option 2 
<button type="submit">Add this product"</button> 
</form>

I'm trying to post the serialized form data into the following JSON format:

products = {
    "ProductA": {
        "option": ["Option 1"] // only 1 checkbox is checked
    },
    "ProductB": {
        "optionAll": "Option All",
        "option": ["Option 1", "Option 2"] // both checkboxes are checked
    }   
}

I've been playing around with mapping the serialized data but couldn't get it into the JSON format like above.

data = $.map($('form').serializeArray(), function(el, i){
    var json = {};
    ???
    return json;
});
console.log(data)

Appreciate your help!

Upvotes: 0

Views: 4436

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

var result = {};  // object to hold final result

$('button[type="submit"]').on('click', function() {

    $('form').each(function() {  // loop start for each form

      var sr = $(this).serializeArray(),
          options = [];

      result[sr[0].value] = {}; // insert Product value and initiate it as object

      $.each(sr, function() {  // loop start for each checkbox

        if(this.name == 'option') {

            options.push(this.value);

        }

      });

      // if all checkbox are checked then insert the property optionAll

      if(options.length == $('input[type="checkbox"][name="option"]',this).length) {

        result[sr[0].value].optionAll = 'Option All';  

      }

      result[sr[0].value].option = options;

   });

   console.log(result);
});

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

To serialize as a JSON string a javascript object, simply use

JSON.stringify(myobject)

So your work is mainly to make the object :

 var products = {
 };

 products['ProductA'] = $('input[name="Products"]').find(':checked').val();

and so on...

But you really should change a little your html : you should really avoid to have identically named inputs. Try to give them an id at least.

Upvotes: 0

Related Questions