jQuery:尝试附加选项以选择标记

时间:2015-04-18 07:04:25

标签: javascript jquery jquery-chosen jquery-append

您好我正在尝试根据输入附加选项以选择标记。但选项不附加。我甚至没有得到错误,所以故障无法理解。

HTML

  <div class="col-lg-5">
      <div class="input-group">
          <label>Select type of Graph</label>    
          <select data-placeholder="Select Field..." id="graph_name" style="width:300px;" name="team_name" class="chosen-select" tabindex="2">

          </select>
      </div>
  </div>

jQuery的:

$('#field_name').change(function() {
  var fieldname = $('#field_name option:selected').val();
  $.post('<?php echo BASE_URL . 'php/processing/formDashboard/graph/showPossibleGraphs.php?id=' . $_GET['id']; ?>', {fieldname: fieldname}, function(data) {
    $.each(data.graphs, function(index, value) {
      $.each(value, function(index, value) {
        console.log(value.id);
        console.log(value.text);
        var option = '<option value="'+value.id+'">'+value.text+'</option>';
        $('#graph_name').append(option);
      });
    });
  });
});

这是截图 This is the image when i selected the option from one dropdown & the data came from script in JSON format

这是我从一个下拉菜单中选择选项时的图像。数据来自JSON格式的脚本

This is the firebug debugging screenshot that shows that data is getting appended but on click it is showing nothing

这是firebug调试屏幕截图,显示数据已被追加,但点击后它没有显示任何内容 我的样本数据如下:

sample data: {
  "status":"OK",
  "response":200,
  "graphs":[[
    {"id":"B","text":"Bar Chart"},
    {"id":"D","text":"Doughnut Chart"},
    {"id":"P","text":"Pie Chart"}
  ]]
}

2 个答案:

答案 0 :(得分:7)

  

基于聊天编辑

由于您正在动态构建select,因此您必须触发所选的插件。

 $('#graph_name').trigger("chosen:updated");

在附加选项后添加它。它会起作用

<强> DEMO

您正试图直接追加字符串。但是你必须附加DOM元素。

  var option = '<option value="'+value.id+'">'+value.text+'</option>';
  $('#graph_name').append(option);

一定是

  var option = $('<option value="'+value.id+'">'+value.text+'</option>');
  $('#graph_name').append(option);

更好的是,而不是在每次迭代时附加到DOM树。加载一个数组,然后在select中设置html()。它会提高性能。

答案 1 :(得分:2)

另一种选择是:

$.each(selectValues, function(key, value) {   
     $('#graph_name')
         .append($("<option></option>")
         .attr("value",key)
         .text(value)); 
});