我有
var updateActive = [{
"id": "1",
"name": "Koka Kola",
"qty": "22",
"price": "333",
"active": "Yes"
}, {
"id": "2",
"name": "Pizza",
"qty": "1",
"price": "1",
"active": "Yes"
}, {
"id": "3",
"name": "Jupi",
"qty": "2",
"price": "25000"
}, {
"id": "4",
"name": "Jupi",
"qty": "333",
"price": "333"
}]
var message =“ “;
像我可以循环的数组
$.each(updateActive, function (_, val) {
val.id;
val.name;
});
但我有问题如何将这些值放在var消息的循环中? 喜欢
<option value="val.id">val.name</option>
答案 0 :(得分:1)
您可以在循环中创建DOM选项元素,并将它们附加到动态创建的选择中,如下所示:
var updateActive = [{
"id": "1",
"name": "Koka Kola",
"qty": "22",
"price": "333",
"active": "Yes"
}, {
"id": "2",
"name": "Pizza",
"qty": "1",
"price": "1",
"active": "Yes"
}, {
"id": "3",
"name": "Jupi",
"qty": "2",
"price": "25000"
}, {
"id": "4",
"name": "Jupi",
"qty": "333",
"price": "333"
}];
var message = "<select class='form-control' required name='article[]'></select>";
var select = $(message).get(0);
$.each(updateActive, function (_, val) {
var option = document.createElement('option');
option.id = val.id;
option.innerHTML = val.name;
select.appendChild(option);
});
alert(select.outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
答案 1 :(得分:0)
<强> jsBin demo 强>
var message = "<select class='form-control' required name='article[]'></select>";
var $msg = $(message); // Convert to jQuery element
var options = ""; // Create a String To concatenate HTML Option Elements
$.each(updateActive, function (idx, val) {
options += '<option value="'+val.id+'">'+val.name+'</option>'; // Concat
});
$msg.html( options ); // Finally set String as Element's HTML
如果没有字符串连接,您可以直接.append()
到元素:
<强> jsBin demo 强>
var message = "<select class='form-control' required name='article[]'></select>";
var $msg = $(message); // Convert to jQuery element
$.each(updateActive, function (idx, val) {
$msg.append('<option value="'+val.id+'">'+val.name+'</option>');
});