如何在单独的组合框中获取数组值

时间:2018-11-23 07:25:11

标签: javascript html ajax

我想使用JavaScript和PHP在单独的组合框中获取数组值。假设我有

这样的数组
  

0:{“ id”:“无”,“名称”:“无”},1:{“ id”:“无”,“名称”:“无”},2:{“ id”: “ write”,“ name”:“ write”}

我希望第一个组合框显示0索引数组,第二个组合框显示1索引数组,依此类推,所有组合框都具有相同的名称。但是,当我完成时,它会在一个组合框中显示所有数组。这是我的代码

var data = [{
  "id": "none",
  "name": "none"
}, {
  "id": "none",
  "name": "none"
}, {
  "id": "write",
  "name": "write"
}]

$.each(data, function(i, item) {

  $('#modules').append('<option value="' + data[i].id + '">' + data[i].name + '</option>');

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="modules"></select>

3 个答案:

答案 0 :(得分:0)

如果您想使用普通的JavaScript来实现此目的,请参见下面的代码段以及所需的输出-从下拉列表中选择对象,并从数组对象中填充文本。

var data = [{
  "id": "none",
  "name": "none"
}, {
  "id": "none",
  "name": "none"
}, {
  "id": "write",
  "name": "write"
}]


function comboBox(data) {
    const select = document.getElementById('modules')
    data.map(object => {
    	let option = document.createElement("option");
        option.value = object.id;
        option.text = object.id;
        select.appendChild(option);  
    })
}

comboBox(data);
<select id="modules"></select>

答案 1 :(得分:0)

您要3个下拉菜单吗?

var data = { 
  "one":   [{ "id": "none", "name": "none 1" }, { "id": "none", "name": "none 1" }, { "id": "write", "name": "write 1" }], 
  "two":   [{ "id": "none", "name": "none 2" }, { "id": "none", "name": "none 2" }, { "id": "write", "name": "write 2" }], 
  "three": [{ "id": "none", "name": "none 3" }, { "id": "none", "name": "none 3" }, { "id": "write", "name": "write 3" }]
}

$.each(data, function(i, item) {
  var $sel = $("<select/>", {
    "name": "data"
  });
  $.each(item, function(i, selItem) {
    $sel.append('<option value="' + selItem.id + '">' + selItem.name + '</option>')
  });
  $('#modules').append($sel);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="modules"></div>

答案 2 :(得分:-1)

我认为您想在下拉菜单中显示数据 只需确保阵列格式正确即可。

var data = [{"id":"none","name":"none"},                
                        {"id":"none","name":"none"},        
        {"id":"write","name":"write"}];

$.each(data,function(i,item){
   $('#modules').append('<option value="'+data[i].id+'">'+data[i].name+'</option>');  });




$('.modules').eq(i).append('<option value="' + data[i].id + '">' + data[i].name + '</option>');