简体   繁体   English

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

[英]jQuery:Trying to append the options to select tag

Hi I am trying to append the options based on input to select tag. 嗨,我试图根据输入附加选项来选择标签。 but options are not appending. 但选项不附加。 I am not even getting the errors so where is the fault not able to understand. 我甚至没有得到错误,所以故障无法理解。

HTML 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: 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);
      });
    });
  });
});

Here is the screenshot 这是截图 这是我从一个下拉列表中选择选项时的图像,数据来自JSON格式的脚本

This is the image when i selected the option from one dropdown & the data came from script in JSON format 这是我从一个下拉列表中选择选项时的图像,数据来自JSON格式的脚本

这是firebug调试屏幕截图,显示数据被追加,但点击它时什么都没有显示

This is the firebug debugging screenshot that shows that data is getting appended but on click it is showing nothing My sample data is this: 这是firebug调试截图,显示数据被追加,但点击它没有显示任何内容我的样本数据是这样的:

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

EDIT Based on Chat 编辑基于聊天

Since you're dynamically forming the select , you must trigger the chosen plugin. 由于您正在动态形成select ,因此必须触发所选插件。

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

Add it after appending the options. 在附加选项后添加它。 It will work 它会工作

DEMO DEMO

You're trying to append the string directly. 你试图直接附加字符串。 But you must append the DOM element. 但是你必须附加DOM元素。

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

It must be 一定是

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

Even better, instead of appending to the DOM tree on every iteration. 更好的是,而不是在每次迭代时附加到DOM树。 Load it an array and then set the html() in the select . 加载一个数组,然后在select设置html()。 It will improve the performance. 它将改善性能。

Another alternative would be: 另一种选择是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM