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

Viewed 58

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?

1 Answers

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>

Related