Donald
Donald

Reputation: 633

How to populate list-group with javascript?

I get the ticket data from a controller using code below:

       $.ajax({
            type: "GET",
            url: "/Tickets/List/",
            data: param = "",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: successFunc,
            error: errorFunc
        });

        function successFunc(data, status) {

            var ds = [];

            // d.ticket_no, d.ticket_subject, d.ticket_date,

            data.forEach((d) => {
                
            });
        }

I don't have an idea on How to display it using the HTML format below?

  <a class="list-group-item list-group-item-action" id="list-tickets-list" data-toggle="tab" 
  href="#ticket-info" role="tab" aria-controls="list-tickets">
  <div class="d-flex w-100 justify-content-between">
      <h5 id="ticket_subject" class="mb-1">**Ticket Subject Example**</h5>
         <small id="ticket_date">**02-Aug-2021**</small>
  </div>
  <p id="ticket_no" class="mb-1"><strong>**TKT-2021010678**</strong></p>
                                        

Upvotes: 0

Views: 220

Answers (1)

CodeBug
CodeBug

Reputation: 1667

var data = [{
    "ticket_no":1234,
  "ticket_subject":"myticker",
  "ticket_date":"1-2-3"
},{
    "ticket_no":1235,
  "ticket_subject":"myticker1",
  "ticket_date":"1-2-4"
}];
var mydiv = document.getElementById('ticketdiv');

data.forEach((d) => {
    mydiv.innerHTML +=`<a class="list-group-item list-group-item-action" id="list-tickets-list" data-toggle="tab" 
  href="#ticket-info" role="tab" aria-controls="list-tickets">
  <div class="d-flex w-100 justify-content-between">
      <h5 id="ticket_subject" class="mb-1">${d.ticket_subject}</h5>
         <small id="ticket_date">${d.ticket_date}</small>
  </div>
  <p id="ticket_no" class="mb-1"><strong>${d.ticket_no}</strong></p>`
            });
<div id="ticketdiv">

</div>

you can use JS innerHTML to get it done, here what I'm doing is looping the data from foreach, and adding HTML content to the div by mydiv.innerHTML +=

you can read more about JS innerHTML here

Upvotes: 1

Related Questions