首页 > 解决方案 > 使用 JSON 对象元素填充选择选项

问题描述

我想使用 JSON Object 中包含的选项填充选择标记: 在此处输入图像描述

您好需要填充此选择:

 <select class="selectpicker" name="iroleinspecteurcommercial" id="iroleinspecteurcommercial" data-live-search="true" data-actions-box="true" multiple></select></br>

来自的信息arr1.libellerole

我试过这段代码但没有结果:

$.each(arr1.libellerole, function(k, v){
        $("#iselectroledirregional").append('<option>'+v+'</option>');
    });

谢谢

标签: javascripthtml

解决方案


Based on the image you've provided, there is no arr1.libellerole. Instead, you have to iterate over every element in the array and access its libellerole property.

Also, the id of the <select> you've given and the one in your JavaScript code don't match.

Try this:

$.each(arr1, function (k, v) {
    $("#iroleinspecteurcommercial").append('<option>' + v.libellerole + '</option>');
});

Example:

var arr1 = [
  {libellerole: 1},
  {libellerole: 2},
  {libellerole: 3},
  {libellerole: 4},
  {libellerole: 5}
];

$.each(arr1, function(k, v) {
  $("#iroleinspecteurcommercial").append('<option>' + v.libellerole + '</option>');
});
<script src = "//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id = "iroleinspecteurcommercial" multiple></select>


推荐阅读