Feed Select with another Select Mysql

1

I'm trying to feed a Select as it was selected in another Select main

<select id="grupo" name="grupo"  >
  <option>Selecionar Grupo</option>
    <?php if(isset($grupo->db->data[0])): ?>
      <?php foreach ($grupo->db->data as $grp) : ?>
        <option value="<?= $grp->grupo_id ?>"><?= $grp->grupo_nome ?>/option>
      <?php endforeach; ?>
    <?php endif; ?>
</select>

Select Secondary

<select name="empresa" id="empresa">
</select>

I'm trying to feed with JS :

$(document).ready(function() {
  $('#grupo').on("change", function() {
    var id = $('select[name=grupo]').val();
    $('#grupo_id').val(id);
    var url = "empresa_fn.php?acao=Json";
    $.getJSON(url, {grupo_id: id}, function (data) {
        // não estou conseguindo atribuir o valores para os options 
        // do select
    });
  });
});
    
asked by anonymous 05.06.2017 / 20:54

1 answer

0

There are several ways you can do it.

The most practical is to use $.each of JQuery

  

In the example JSON return: ["id": "1", "value": "Example 1"}, {"id": "2", "value": "Example 2"}]

$.getJSON(url, {grupo_id: id}, function (data) {
    $.each(data, function (i, item) {
        $('#empresa').append($('<option>', { 
            value: item.id,
            text : item.value 
        }));
    });
}

You can also create a function:

function populate(selector,json_values) {

  for(var i = 0; i < json_values.length; i++) {
     var obj = json[i];
     $(selector).append('<option value="'+json[i].id+'">'+json[i].value+'</option>')
  }
}

populate('#empresa',data);

A very common practice before you start creating new options is to clean select using .empty() ( $("#empresa").empty() ), this will make the field clean for new data entry.

/ p>     

05.06.2017 / 21:04