0

I have this HTML

<select class="form-control" required name="article">
    <option value="Coca Cola">Coca Cola</option>
</select>
<input class="form-control number-input" value="" name="qty" type="text">


<select class="form-control" required name="article">
    <option value="Jupi">Jupi</option>
</select>  
<input class="form-control number-input" value="" name="qty" type="text">


<select class="form-control" required name="article">
    <option value="Fanta">Fanta</option>
</select>
<input class="form-control number-input" value="" name="qty" type="text">

And

JS

var invoiceNumber = 1;

var articles = $('[name~=article]').map(function () {
    return $(this).val()
}).get();
var qty = $('[name~=qty]').map(function () {
    return $(this).val()
}).get();

What i need is to get new JSON that will look like this

var invoicesGet = [{
    "invoice": "1",
    "article": "Coca Cola",
    "qty": "2042"
}, {
    "invoice": "1",
    "article": "Jupi",
    "qty": "232"
}, {
    "invoice": "1",
    "article": "Fanta",
    "qty": "45"
}]

This is working fiddle what i have for now: http://jsfiddle.net/b33kvd3L/

I think i got all elements value, order will be that way, but i dont know how to combine all this json to one, and add invoiceNumber? I dont know how many inouts will be added they are dinamicly add

Miomir Dancevic
  • 6,726
  • 15
  • 74
  • 142
  • What about this topic http://stackoverflow.com/questions/11338774/serialize-form-data-to-json like so http://jsfiddle.net/b33kvd3L/1/ – Robert Oct 01 '14 at 14:57

2 Answers2

1

Make an array of objects after your JS:

var invoicesGet = [];
for (var i in articles) {
    invoicesGet.push({
        invoice: invoiceNumber,
        article: articles[i],
        qty: qty[i]
    });
}

Updated live code: http://jsfiddle.net/b33kvd3L/3/

Produce output like: [{"invoice":1,"article":"Coca Cola","qty":"12"},{"invoice":1,"article":"Jupi","qty":"34"},{"invoice":1,"article":"Fanta","qty":"56"}]

Nicolas Albert
  • 2,586
  • 1
  • 16
  • 16
0

Find the next qty input using .next() and return the object then convert to JSON.

var articles = $('[name~=article]').map(function () {
    var qtyVal = $(this).next("[name=qty]").val();
    return { 
        invoice: invoiceNumber, 
        article: $(this).val(),
        qty: qtyVal
    };
}).get();

JSFiddle: http://jsfiddle.net/b33kvd3L/16/

Ted Plaisted
  • 121
  • 5