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?
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);
});
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With