0
I have the following idea that the moderator Sergio sent
var obj = [JSON]
var mydiv = document.getElementById("tabLista");
mydiv.innerHTML = "";
var ul = document.createElement("ul");
mydiv.appendChild(ul);
var escolhidas = [];
obj.forEach(function(obj) {
obj = obj.List;
var li = document.createElement("li");
ul.appendChild(li);
Object.keys(obj).forEach(function(chave) {
var div = document.createElement("div");
div.classList.add(chave);
div.textContent = obj[chave];
li.appendChild(div);
});
var checkbox = document.createElement("input");
checkbox.type = 'checkbox';
checkbox.addEventListener('change', function() {
this.closest('li').classList.toggle('selecionado', this.checked);
if (this.checked) escolhidas.push(obj);
else escolhidas = escolhidas.filter(function(el) {
return el != obj;
});
console.log(escolhidas);
});
li.appendChild(checkbox);
});
Only when entering the json my server responds the script does not recognize the keys, just print
[object Object]
[object Object]
[object Object]
Json that my server responds
{
"api": "api",
"List": [{
"tipo": "1",
"data": "10/10/2017",
"Hora": "11:38",
"Size": "0",
"Nome": "Marcelo"
}, {
"tipo": "1",
"data": "10/10/2017",
"Hora": "11:38",
"Size": "0",
"Nome": "Pedro"
}, {
"tipo": "1",
"data": "10/10/2017",
"Hora": "11:38",
"Size": "0",
"Nome": "Lucas"
}],
"arq": "1",
"paste": "2"
}
Json From the original idea
var obj = [{
nome: 'a',
data: '13/09/2017'
},
{
nome: 'b',
data: '13/09/2017'
},
{
nome: 'c',
data: '13/09/2017'
},
{
nome: 'd',
data: '13/09/2017'
},
]
Obigado :)
Which section is this printed on? Because it is printing an object, you may have to print a string or work the object.
– BrTkCa
What if you switch console.log(chosen) by console.log(JSON.stringify(chosen, null, 2)); what displays?
– Tom Melo
It is being printed in the div tabLista, with Sergio’s json works normally, but with mine not, changing the console.log back "Null"
– Stan
@Planetwar having trouble sending to server or receiving from server?
– Sergio
Receive json and print to li
– Stan
Okay, what is the Javascript code that fetches JSON?
– Sergio
Another thing, you’re naming it after
JSON
to the variable?JSON
(large letter) is a reserved word in Javascript, you should use another.– Sergio
No, I just put JSON there to show where my json goes, but I’m putting the JSON.parse response there (req.responseText);
– Stan
And then you’re wearing
var obj = JSON.parse(req.responseText);
orvar obj = [JSON.parse(req.responseText)];
?– Sergio
I am using var obj = JSON.parse(req.responseText);
– Stan
Okay, so switch to
var obj = JSON.parse(req.responseText).List;
and then take theobj = obj.List;
within the.forEach
. The problem is that you are passing the object and not an array. Or leave it as is but pass an array in case you have several of these Jsons.– Sergio
It worked perfectly, thank you for clarifying :)
– Stan