Miomir Dancevic
Miomir Dancevic

Reputation: 6852

Getting JSON from elements Jquery?

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

Upvotes: 0

Views: 74

Answers (2)

Ted Plaisted
Ted Plaisted

Reputation: 121

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/

Upvotes: 0

Nicolas Albert
Nicolas Albert

Reputation: 2596

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"}]

Upvotes: 1

Related Questions