Shubham Sinha
Shubham Sinha

Reputation: 79

Multiple input fields to JSON

I've a form which has input fields as shown in figure below. Each time I click the add button, the row containing the input fields is appended. enter image description here

The html code goes like this :

<div class="row">
         <div class="row ifields">
                <div class="col-sm-3 form-group">
                </div>
                <div class="col-sm-2 form-group">
                    <input type="text" class="form-control" name="pname" placeholder="Product Name" />
                </div>
                <div class="col-sm-2 form-group">
                    <input type="number" min="1" class="form-control text-center" name="pquantity" placeholder="Product Quantity" />
                </div>
                <div class="col-sm-2 form-group">
                    <select class="form-control text-center" name="qtype">
                        <option value="g">g</option>
                        <option value="Kg">Kg</option>
                        <option value="ml">ml</option>
                        <option value="L">Lt.</option>
                        <option value="pc">Pc</option>
                    </select>
                </div>
                <div class="col-sm-2 form-group">
                    <input type="text" class="form-control text-center" name="pcost" placeholder="Product Cost" />
                </div>
                <div class="col-sm-1"><button class="btn btn-default add-btn">Add</button></div>
              </div>
    </div>
    <div class="row iclone"></div>
 </div>

And the Jquery code :

$(document).ready(function(){
        $('.add-btn').click(function(){
            var cl = $('.ifields').first('.row').clone(true);
            $('.iclone').append(cl);

        });
});

I want to go through each row and create a JSON file. For ex:

[{
  "product" : "A",
  "quantity" : "100",
  "quantitytype" : "g",
  "cost" : "100"
},
...
....
]

How to do create this JSON output ? Please guide.

Upvotes: 1

Views: 6000

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use map() to create the required array of objects. Try this:

var data = $('.row.ifields').map(function() {
    return {
        product: $(this).find('[name="pname"]').val(),
        quantity: $(this).find('[name="pquantity"]').val(),
        quantityttype: $(this).find('[name="qtype"]').val(),
        cost: $(this).find('[name="pcost"]').val()
    };
}).get();

You can then use the data array as required - presumably in a $.ajax() call.

Working example

Upvotes: 2

Related Questions