我有这个 的 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">
并且
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? 我不知道会添加多少次输入,他们是dinamicly add
答案 0 :(得分: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"}]
答案 1 :(得分: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/