Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate dynamic HTML with jQuery in a loop and a JSON with parameters?

I would like to generate a HTML file out of an JSON in a loop. For example that's the result I want:

<div class="card">
    <p>My name is: Peter</p>
    <!-- another code -->
    <p>My job is: Programmer</p>
    <!-- some more code -->
</div>

<div class="card">
    <p>My name is: John</p>
    <!-- another code -->
    <p>My job is: Programmer</p>
    <!-- some more code -->
</div>

<!-- and so on ... -->

But I want to generate all that HTML (that means: all the "card"-divs) dynamically just out of an simple JSON like:

[
    { "Name": "Peter", "Job": "Programmer" },
    { "Name": "John", "Job": "Programmer" },
    { "Name": "Kevin", "Job": "Scientist" },
]

Unfortunately I'm just learning some JS/jQuery and don't know exactly, how to do that with jQuery in a loop. Anyone some help?

like image 248
Kabalaba Avatar asked Nov 02 '25 01:11

Kabalaba


2 Answers

Try this one:

function createCard(cardData) {
  var cardTemplate = [
    '<div class="card">',
    '<p>My name is: ',
    cardData.Name || 'No name provided',
    '</p>',
    '<p>My job is: ',
    cardData.Job || 'No job provided',
    '</p></div>'
  ];

  // a jQuery node
  return $(cardTemplate.join(''));
}

var data = [
    { "Name": "Peter", "Job": "Programmer" },
    { "Name": "John", "Job": "Programmer" },
    { "Name": "Kevin", "Job": "Scientist" },
];

var cards = $();
// Store all the card nodes
data.forEach(function(item, i) {
  cards = cards.add(createCard(item));
});

// Add them to the page... for instance the <body>
$(function() {
  $('body').append(cards);
});
like image 190
kidwon Avatar answered Nov 04 '25 17:11

kidwon


Take a look.
https://jsfiddle.net/c0w6jbpa/

$.each(arr, function(i){ //Loop the array
   var templateString = '<div class="card"><p>My name is: '+arr[i].Name+'</p><p>My job is: '+arr[i].Job+'</p></div>'; 
   //You can get the prop of array with arr[i].Name
   $('#test').append(templateString);
})

You can use $.each for loop an array.
Link: http://api.jquery.com/jquery.each/

like image 34
Roy Bogado Avatar answered Nov 04 '25 17:11

Roy Bogado