javascriptjqueryjquery-chosenjquery-append

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

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

Here is the screenshot This is the image when i selected the option from one dropdown & the data came from script in JSON format

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

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

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:

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

Solution

  • EDIT Based on Chat

    Since you're dynamically forming the select, you must trigger the chosen plugin.

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

    Add it after appending the options. It will work

    DEMO

    You're trying to append the string directly. But you must append the DOM element.

      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. Load it an array and then set the html() in the select. It will improve the performance.