jquery JSON检索并根据JSON中的数据将值放入选择框

zaqlnxep  于 2023-10-17  发布在  jQuery
关注(0)|答案(1)|浏览(95)

我有一个JSON数据从数据库中,我想把设置选择的基础上的数据,我检索的JSON。下面是我的代码。

  • jQuery*
var objJSON = JSON.parse(response['data'][0].certificate);
var inputs = "";
$.each(objJSON, function (i, v) {
    inputs += '<select class="form- " name="department[]"><option>選択してください</option><option>department one</option><option>industry two</option><option>industry three</option> <option>industry four</option></select>';
});
$("#input_container").html(inputs);

HTML

<div id="input_container"></div>

下面是我的json的console.log输出。

我怎么能有一个输出就像下面?

kqhtkvqz

kqhtkvqz1#

为什么要为每个选项创建单独的 < select >
为什么不能只生成 < option >

var objJSON = ['industry one', 'second industry', 'third ...']; //JSON.parse(response['data'][0].certificate);


setTimeout(function(){ // timeout for DEMO only

  $('#DepartmentsDropDownList').empty();

  
  //if(isOptional || notRequiredInput)
  //  $('#DepartmentsDropDownList').append('<option value=""> -- Select an item</option>');
  
  for(var i in objJSON) {
      $('#DepartmentsDropDownList').append('<option value="'+ objJSON[i] +'">'+ objJSON[i] +'</option>');
  }

}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="input_container">
  
  <select id="DepartmentsDropDownList" class="form-control" name="department[]">
    <option> -- Loading items...</option>
  </select>

</div>

如果您想为每个项目单独选择

var objJSON = ['industry one', 'second industry', 'third ...']; //JSON.parse(response['data'][0].certificate);


setTimeout(function(){ // timeout for DEMO only

  $('#inputs_container').empty();

  
  //if(isOptional || notRequiredInput)
  //  $('#DepartmentsDropDownList').append('<option value=""> -- Select an item</option>');
  
  for(var i in objJSON) {
      $('#inputs_container').append('<div> <select><option value="'+ objJSON[i] +'">'+ objJSON[i] +'</option></select> </div>');
  }

}, 1000);
<div id="inputs_container"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

所选认证解决方案

var objJSON = ['certification one', 'certification two', 'certification five']; //JSON.parse(response['data'][0].certificate);
      $('#DepartmentsDropDownList').val(objJSON);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="input_container">
  
  <select id="DepartmentsDropDownList" class="form-control" name="department[]" multiple="multiple" style="height: 100px;">
    <option value="certification one">certification one</option>
    <option value="certification two">certification two</option>
    <option value="certification three">certification three</option>
    <option value="certification four">certification four</option>
    <option value="certification five">certification five</option>
  </select>

</div>

相关问题