2014-10-01 222 views
0

我有這個 HTML從元素Jquery獲取JSON?

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

而且

JS

var invoiceNumber = 1; 

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

什麼,我需要的是讓新的JSON看起來像這樣

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

這是工作撥弄我有什麼現在: http://jsfiddle.net/b33kvd3L/

我想我得到了所有的元素值,訂貨會是這樣,但我不知道怎麼這一切JSON結合爲一,並添加invoiceNumber? 我不知道有多少inouts將加入他們dinamicly添加

+0

什麼這個話題http://stackoverflow.com/questions/11338774/serialize-form-data-to-json像這樣http://jsfiddle.net/b33kvd3L/ 1 / – Robert 2014-10-01 14:57:36

回答

1

創建一個對象數組你的JS後:

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

更新實時代碼:http://jsfiddle.net/b33kvd3L/3/

產生輸出,如:[{"invoice":1,"article":"Coca Cola","qty":"12"},{"invoice":1,"article":"Jupi","qty":"34"},{"invoice":1,"article":"Fanta","qty":"56"}]

0

使用.next()查找下一個qty輸入並返回該對象,然後轉換爲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/