Multilevel list menu with JSON and jQuery Mobile - javascript

I try to reach following structure
a list of (distinct!) categories
Category 1
Category 2
Category n
And each Category links to the posts within the Category. And the posts link to the content
Post 1 Cat 1 --> Content Post 1 Cat 1
Post 2 Cat 2 --> Content Post 2 Cat 1
Question: I don't know how to create the distinct list of categories which leads to the posts. Any solutions?
This is my JSON example (this is from the json api plugin in wordpress)
{"status": "ok",
"count": 10,
"count_total": 20,
"pages": 2,
"posts": [
{
"id": 86,
"type": "post",
"slug": "inaktiviert",
"url": "http://localhost/wordpress/?p=86",
"status": "publish",
"title": "Post 1 Cat1",
"content": "his is content for Post1 Cat 1.",
"date": "2014-03-04 15:09:51",
"modified": "2014-03-04 15:09:51",
"categories": [
{
"id": 1,
"title": "Category 1",
"description": "",
"parent": 0,
"post_count": 4
}
],
},
{
"id": 84,
"type": "post",
"slug": "kann-nicht-aktualisiert-werden",
"url": "http://localhost/wordpress/?p=84",
"status": "publish",
"title": "Post 2 Cat1",
"content": "<p>This is content for Post2 Cat 1.</p>\n",
"date": "2014-03-04 15:09:25",
"modified": "2014-03-04 15:09:25",
"categories": [
{
"id": 1,
"title": "Category 1",
"description": "",
"parent": 0,
"post_count": 4
}
],
},
{
"id": 74,
"type": "post",
"slug": "dieses-symbol-zeigt-an",
"url": "http://localhost/wordpress/?p=74",
"status": "publish",
"title": "Post 1 Cat2",
"content": "This is Content for Post1 Cat 2",
"date": "2014-03-04 15:06:47",
"modified": "2014-03-04 15:06:47",
"categories": [
{
"id": 2,
"title": "Category 2",
"description": "",
"parent": 0,
"post_count": 3
}
],
}
]}
And this my JS
$(document).on("pagecreate", "#page1", function(){
var liste = $('#liste');
var AllListItems = '';
var AllDynamicPages = '';
$.each(daten.posts, function(index1, data) {
var postid = data.id;
var postTitle = data.title;
var postContent = data.content;
for (var i = 0; i< data.categories.length; i++) {
var catid = data.categories[i].id;
var catTitle = data.categories[i].title;
AllListItems += '<li>' + postTitle + '</li>';
AllDynamicPages += '<div data-role="page" data-add-back-btn="true" id="page' + postid + '"><div data-role="header"><h1>' + postTitle + '</h1></div><div data-role="content">' + postContent + '</div></div>'
}
});
liste.empty().append(AllListItems).listview("refresh");
$("body").append(AllDynamicPages);
});
DEMO

I would approach it this way: Instead of a list, create a collapsible set where each child collapsible is a category, and each category collapsible contains a list of posts.
Here is your updated FIDDLE
So the top level HTML markup would be a collapsible set:
<div id="thelist" data-role="collapsibleset" data-theme="a" data-content-theme="a">
</div>
Then the code:
var liste = $('#thelist');
var AllDynamicPages = '';
$.each(daten.posts, function(index1, data) {
var postid = data.id;
var postTitle = data.title;
var postContent = data.content;
for (var i = 0; i< data.categories.length; i++) {
var catid = data.categories[i].id;
var catTitle = data.categories[i].title;
//see if we already have this category, if not create new collapsible
var $cat = $("#cat" + catid);
if ($cat.length == 0){
$cat = $('<div id="cat' + catid + '" data-role="collapsible"><h3>' + catTitle + '</h3><ul data-role="listview"></ul></div>');
liste.append($cat);
}
//create post link in category collapsible list
var postlink = '<li>' + postTitle + '</li>';
$cat.find("ul").append(postlink);
AllDynamicPages += '<div data-role="page" data-add-back-btn="true" id="page' + postid + '"><div data-role="header"><h1>' + postTitle + '</h1></div><div data-role="content">' + postContent + '</div></div>'
}
});
liste.enhanceWithin();
$("body").append(AllDynamicPages);
It is the same iteration as you had before, but now for each category, we check if there is already a collapsible for that category. If there is not we create one and add it to the set. Then we create a link for the post and add it the list widget within the category collapsible.
Finally we call .enhanceWithin() to apply jQM styling.
The dynamic pages part stays exactly the same.

Related

How can I give a different class for each header in a loop

I've been trying to make a HTML page where each box represents 1 item that has been ordered. Here's the HTML for the box:
<div id="boxMaster" class="small-box bg-info" class="box-PEDIDO" hidden>
<a class="nmroPedido small-box-header" id="header"></a> <a class="float-right" id="dataEntrega">28/09/2021
16:00</a>
<hr>
<div class="inner">
<p id="nomeproduto"></p>
</div>
<div class="icon">
<i class="fas fa-shopping-cart" id="carrinho"></i>
</div>
<hr id="footer" class="baixoHr">
<a href="#" class="small-box-footer"> Fruta > Tropical > Manga > Tommy   
</a>
</div>
And this is how I'm treating the data to feed it:
fetch('http://---.--.14.--:--/pedidos/', {
method: 'GET',
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NCwiaWF------yNTkwLCJleHAiOjE2MzM3Nzg5OTB9.XwrGFhLiGJ0YS5FHjn7Xo',
'Content-type': 'application/json'
}
})
.then(function (response) {
return response.json();
})
.then(function (jsonResponse) {
// console.log(jsonResponse);
var DadosPedidos = jsonResponse;
pedidosArray = jsonResponse.length;
for (let pedidos of DadosPedidos) {
let a = 0;
for (let i = 0; i < pedidos.items.length; i++) {
let pedidosLength = pedidos.items.length;
let lengthPedidos = pedidos.nroPedCliente;
var boxClonado = $("#boxMaster").clone(true);
$(boxClonado).appendTo("#preparando").removeAttr("hidden", "style").removeAttr("id").addClass(`${pedidos.id}-${pedidos.items[i].codItem}`);
$(".nmroPedido").addClass(`${pedidos.items[i].codItem}`);
let nomeClasses = `${pedidos.id}-${pedidos.items[i].codItem}`;
let h3quantidade = `${pedidos.id}-${pedidos.items[i].codItem}`;
$("." + nomeClasses).append(`<p>${pedidos.items[i].codItem}</p>`);
$("." + h3quantidade).append(`<h3 class="h3qtd">${pedidos.items[i].qtdPedida}</h3>`);
//$("." + headerPedido).append(`Nº do Pedido: ${pedidos.nroPedido}`);
let data = new Date((pedidos.dataEntrega).substring(0, 10));
let dataEnt = ((data.getDate())) + "/" + ((data.getMonth() + 1)) + "/" + data.getFullYear();
}
}
As you can see, I managed to give a unique class to each box (that represent 1 item) at the end of the line:
$(boxClonado).appendTo("#preparando").removeAttr("hidden", "style").removeAttr("id").addClass(`${pedidos.id}-${pedidos.items[i].codItem}`);
And also managed to do it for the quantities as well. The point is, I'm not being able to do it with the <a class="nmroPedido" id="header>, as the code is printing all -${pedidos.items[i].codItem} codItem all at once in the same class, for every <a id="header> there is. Therefore, I can't set individual "nroPedido" for the box header.
Here's the array I'm getting from the fetch, in case that helps:
https://imgur.com/a/c10ER4X
What am I missing? How can I make it work?
This should do it. Just as example. You have a nested Object and you have to iterate through it with two each loops. Then you can append different unique id's. Then it's easy to create the correct HTML by JSON.
var arr = [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
{
"id": "1003",
"type": "Blueberry"
},
{
"id": "1004",
"type": "Devil's Food"
}
]
}
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
}]
},
},
{
"id": "0003",
"type": "donut",
"name": "Old Fashioned",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
}
]
}
}
]
//console.log(arr);
var markup = '';
$.each(arr, function(key, value) {
key = key + 1;
markup += '<a class="nmroPedido-' + key + ' small-box-header" id="header-' + key + '"></a> <a class="float-right" id="dataEntrega">' + value.id + '</a>'
$.each(value.batters.batter, function(key, v) {
//console.log('id', v.id);
markup += ' <div class="inner"><p id="nomeproduto">' + v.type + '</p></div>';
});
});
$('#boxMaster').append(markup);
//console.log(markup);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxMaster"></div>

How can I output JSON data to an HTML table?

I have some data which is being filtered in the code below. The filter works well. I've added an 'onclick' function to a button in my HTML and my data shows on screen no problem, but what I would like is when I click the button, It shows a table with the filtered data in it, and a way to exit the table, either by a box closing or click the button again and it disappears. I don't mind which.
function loadPRFilter(){
var surgerySearchTerm = "pr";
var data = jsonArray.filter(jsonObject => jsonObject.surgeryType.includes(surgerySearchTerm));
var mainContainer = document.getElementById("pr");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = 'Name: ' + data[i].name + ' ' +'Score: '+ data[i].score + ' '+ 'Severity:'+' '+ data[i].severity;
mainContainer.appendChild(div);
console.log("Filtered pr");
console.log(data);
}
};
here is my data:
var jsonArray =[
{
"ID": 1 ,
"name": "sub conjunctival haemorrhage",
"score" : 1,
"surgeryType": ["scleral buckle"] ,
"severity" : "mild"
},
{
"ID": 2,
"name": "dry eye",
"score": 5,
"surgeryType":[ "pr" ],
"severity" : "moderate"
},
{
"ID": 3,
"name": "ha's",
"score": 5,
"surgeryType":["general", "scleral buckle", "ppv", "pr"],
"severity" : "moderate"
}

How to display nested JSON object in the form of table and rest JSON value as simple text

I want to display nested JSON objects.
This is what I have done so far:
orders = [
{ "custname": "Jack Smith", "mobile": "425361434", "location": "Sector 14", "slot": "12PM2PM", "value": 72.6, "items": [{ "prodcode": "PEP122", "quantity": 2 }, { "prodcode": "COK238", "quantity": 4 }] },
{ "custname": "Mary Gomes", "mobile": "723476123", "location": "Sector 22", "slot": "4PM6PM", "value": 130.60, "items": [{ "prodcode": "SUN677", "quantity": 2 }, { "prodcode": "LUX831", "quantity": 4 }, { "prodcode": "DET810", "quantity": 1 }] },
{ "custname": "Tim May", "mobile": "835099614", "location": "Pioneer Chowk", "slot": "Before 10AM", "value": 705, "items": [{ "prodcode": "GAR004", "quantity": 6 }, { "prodcode": "RB0277", "quantity": 3 }, { "prodcode": "MIR411", "quantity": 2 }] }
];
function showAllOrder() {
showtable();
}
function showtable() {
for (var i = 0; i < orders.length; i++) {
order = orders[i];
var str = "<div><div class='cell22' onclick=clicked(0)>Product</div>";
str = str + "<div class='cell22' onclick=clicked(1)>Qantity</div>";
var len = orders[i].items.length;
for (var j = 0; j < len; j++) {
for (var x = 0; x <)
//this value as simple text form above the table
var cost = ("Coustomer Name :" + order.custname);
var mob = (" Mobile :" + order.mobile);
var loc = (" Location :" + order.location);
var del = (" Delivery Slot :" + order.slot);
//this value in the form of table
var prod1 = "<div class='cell11'>" + orders[i].items[j].prodcode + "</div>";
var qty1 = "<div class='cell11'>" + orders[i].items[j].quantity + "</div>";
var row = "<div>" + cost + mob + loc + del + prod1 + qty1 + "</div>";
str = str + row;
}
}
var element = document.getElementById("mytable01");
element.innerHTML = str;
}

How to loop through jason data and display it in data list tag (dl)

I'm trying to loop through some JSON data (var mydata) and mydata is an array of two elements, the second element in the array
mydata[1] is a multidimensional array, I need to display the first element i.e mydata[0] in a dt and display elements from mydata[1] in a dd within that.
I tried every option but I'm really stuck and I need any help on this. Below is my code:
var mydata = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
function getCategories(id){
$.ajax({
url: '{$getcatUrl}',
type: 'POST',
data: {category_id: id},
success: function (data) {
data = jQuery.parseJSON(data);
//console.log(data); return;
if(data.length > 0){
firstdata = data[0];
secdata = data[1];
for(var i = 0; i < firstdata.length; i++) {
level_1 = firstdata[i].name;
level_1_id = firstdata[i].id;
for(var j = 0; j< secdata.length; j++){
if(secdata[i][j] !== undefined){
level_2='';
level_2 = secdata[i][j].name;
level_2_id = secdata[i][j].d;
}
console.log(level_2);
}
var dldata = $(
'<dl>'+
"<dt href='" + level_1_id + "'>" + level_1 + "</dt>"+
"<dd href='" + level_2_id + "'>" + level_2 + "</dd>"+
'</dl>'
);
}
}else{
console.log('no item for this categories');
}
},
error: function(jqXHR, errMsg) {
// handle error
console.log(errMsg);
}
});
}
The var level_1 and level_1_id works fine, but i keep getting error for variable level_2, the error says can't read property 'name' of undefined, any solution to this problem will be appreciated and am also open to new ideas about doing it better,
Essentially the problem is that you overwrite the level_1 and level_2 variables each time your for loops run. So by the time you get to the code which makes the HTML, they have been overwritten multiple times and only the last version remains, and you only print that once in any case.
This will resolve it - in this case by generating the HTML elements directly within each loop, although you could of course do it by appending to a variable and then outputting everything at the end, if that's your preference.
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
var content = $("#content");
firstdata = data[0];
secdata = data[1];
for (var i = 0; i < firstdata.length; i++) {
var dl = $("#content").append("<dl/>");
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dd>");
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>");
}
}
}
content.append(dl);
} else {
console.log('no item for this categories');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>

How to read array inside JSON Object this is inside another array

I am newbie to JSON, I am parsing a JSON Object and i was struck at a point where i have to read the array Elements inside a Object, that is again in another array..
Here is MY JSON
{
"DefinitionSource": "test",
"RelatedTopics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/a5e4a93a.jpg"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Result": "",
"Icon": {
"URL": "xyz"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Topics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/10d02dbf.jpg"
},
"FirstURL": "https://duckduckgo.com/Snake_Indians",
"Text": "sample"
},
{
"Result": "sample",
"Icon": {
"URL": "https://duckduckgo.com/i/1b0e4eb5.jpg"
},
"FirstURL": "www.google.com",
"Text": "xyz."
}
]
}
]
}
Here I need to read URL ,FIRSTURL and Text from RelatedTopics array and Topics array..
Can anyone help me. Thanks in advance.
Something like this
function (json) {
json.RelatedTopics.forEach(function (element) {
var url = element.Icon ? element.Icon.URL : 'no defined';
var firstURL = element.FirstURL ? element.FirstURL : 'no defined';
var text = element.Text ? element.Text : 'no defined';
alert("URL: " + url + "\nFirstURL: " + firstURL + "\nText: " + text);
if (element.Topics)
{
element.Topics.forEach(function (topicElement) {
alert("Topics - \n" + "URL: " + topicElement.Icon.URL + "\nFirstURL: " + topicElement.FirstURL + "\nText: " + topicElement.Text);
});
}
});
};
Look fiddle example
Loop through json Array like,
for(var i=0; i< RelatedTopics.length;i++){
if($.isArray(RelatedTopics[i])){
for(var j=0; j< RelatedTopics[i].Topics.length;j++){
var topics=RelatedTopics[i].Topics[j];
var text = topics.Text;
var firsturl = topics.Firsturl;
var url = topics.Icon.url;
}
}
}
if you want push it an array variable

Categories

Resources