Select Feed with another Select Mysql

Asked

Viewed 104 times

1

I’m trying to feed a Select according to what was selected in another Select leading

<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 Secundário

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

1 answer

0


There are several ways you can do it.

The most practical is to use the $.each jquery

Taking as return the example JSON: [{"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 
        }));
    });
}

There is also the possibility for you to 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 is before you start creating the new options it is interesting to clear the select using the .empty() ( $("#empresa").empty() ) , this will make the field clean for new data entry.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.