Combo select does not work

0

There are days trying to solve this problem in the list of subcategories but, to no avail. Any solution ? Do not want to show subcategories in select

NOTE: In PHP I made return $subcategorias->fetchAll(\PDO::FETCH_ASSOC); when I took the subcategories in the bank

Print

Code

$("select[name=categoria]").change(function(){
    $("select[name=subcategoria]").html('<option value="" selected="selected">Carregando...</option>');
    $.post(split[0] + "/combo/categoria", {
            categoria: $(this).val()
    }, function(retorno){
        $.each(retorno.subcategoria, function(i, val){
            var subcategoria = '<option value="'+retorno.subcategoria[i].subcategoria+'">'+retorno.subcategoria[i].subcategoria+'</option>';
            $("select[name=subcategoria]").html(subcategoria);
        });
    });
});
    
asked by anonymous 19.02.2017 / 03:31

1 answer

1

If your return is a list of objects:

[
  {subcategoria: "Artesanato"},  
  {subcategoria: "Esculturas"},
  {subcategoria: "Ferramentas"},
  {subcategoria: "Livros"}
];

It does not make sense for you to interact with the subcategoria property, since it only exists in elements belonging to the list, as you did in:

$.each(retorno.subcategoria, function(i, val){
    var subcategoria = '<option value="'+retorno.subcategoria[i].subcategoria+'">'+retorno.subcategoria[i].subcategoria+'</option>';
    $("select[name=subcategoria]").html(subcategoria);
});

Correct is to break in on the return itself and access the subcategoria property of the present value in the list:

$.each(retorno, function(i, val) {
// -----------^
    var subcategoria = '<option value="'+val.subcategoria+'">'+val.subcategoria+'</option>';
    // ----------------------------------^ --------------^ ----^ --------------^
    $("select[name=subcategoria]").append(subcategoria);
    // ----------------------------^
});
  

Note : Comments entered in the code in the format ---^ indicate the points where the changes occurred relative to the original code and therefore deserve more attention.

Note also that it is necessary to replace the html method with append , since the first always overrides the current value and, if used, only the last subcategory of the list would appear. In order to appear all, the append method is used, which only inserts the new value at the end of the current value.

Example

const RETORNO = '[{"subcategoria": "Artesanato"},{"subcategoria": "Esculturas"},{"subcategoria": "Ferramentas"},{"subcategoria": "Livros"}]';

$(() => {
  var list = $("#list");
  $.each(JSON.parse(RETORNO), (key, value) => {
  //-----^ Aqui você converte seu retorno, que é uma string, para objeto
    let option = "<li>" + value.subcategoria + "</li>";
    list.append(option);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulid="list"></ul>
    
19.02.2017 / 04:11