If your return is a list of objects:
[
{subcategoria: "Artesanato"},
{subcategoria: "Esculturas"},
{subcategoria: "Ferramentas"},
{subcategoria: "Livros"}
];
It makes no sense for you to interact on the property subcategoria
, because it only exists in the 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);
});
The correct thing is to enter the return itself and access the property subcategoria
of the 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 inserted in the code in the format ---^
indicate the points at which the changes occurred in relation to the original code and therefore deserve greater attention.
Also note that it is necessary to replace the method html
for append
, because the first always overwrites the current value and, if used, only the last subcategory of the list would appear. In order to appear all, the method is used append
, 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>
<ul id="list"></ul>
Displays the following console error: Uncaught Typeerror: Cannot use 'in' Operator to search for 'length' in [{"subcategory":"Handicraft"},{"subcategory":"Sculptures"},{"subcategory":"Tools and Materials"},{"subcategory":"Books"},{"subcategory":"Paintings"},{"subcategory":"Other"}]
– Jonathan Silva
Probably because you didn’t convert the return to object.
– Woss
I’m layman yet kkkk can tell me how I would do that?
– Jonathan Silva
I edited the example I gave in the reply, putting how you can make the conversion.
– Woss
Perfect =D But when you show the subcategories, you get the "Loading..." option as Selected hahahaha. How can I take after loading the subcategories, to finish here with golden key ? :)
– Jonathan Silva
Use the method
hide
jQuery, but I’ll leave that to you. Just look at the documentation.– Woss
Thank you for your patience and help, vlw :)
– Jonathan Silva