JavaScript loop printing a HTML code - javascript

I have this HTML code:
<div class="content">
<article class="underline">
<a href="incidente.html"><img id="incidente"
src="img/buraco.jpg" alt="Incidente" /></a>
<h2></h2>
<p id="desc">Esse buraco na rua Montes Claros já está há 1 ano
trazendo transtornos aos moradores</p><p></p>
<div class="date" id="date"></div>
<img class="tick" alt="não resolvido" src="img/no-tick.png">
<img class="apoio" alt="apoiar" src="img/apoio.png">
</article>
And this ajax that receive an array:
$.ajax({
type: "GET",
url: "http://localhost/again/www/index.php",
dataType: "json",
success: function (data) {
var tit = "";
// Loop over each object
for (var $i = 0; $i < data.length; $i++) {
var object = data[$i];
tit+= object.titulo;
}
$('#tit').html(tit);
}
});
</script>
Now, it is inserting everything in the same HTML code(off course,because I don't have a foreach), but I would like to show this HTML for each row(each "tit") that i am receiving...Can someone help me?

What I understand is this: You have an array with text that you want to loop through, and display.
If this was your array:
["Text 1", "Text 2", "Text 3", "Text 4", "Text 5"]
then you want this to be displayed
<element>Text 1</element>
<element>Text 2</element>
<element>Text 3</element>
<element>Text 4</element>
<element>Text 5</element>
The problem in your code
The problem I see in your code is that you are using jquery's .html(arrayItem) which will overwrite any existing text inside of the element.
Instead look at my solution: (http://jsfiddle.net/ProgrammerKid/v6upsLp8/)
HTML
<div id="tit"></div>
JavaScript
$(document).ready(function () {
var tit = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5"];
for (var i in tit) {
var element = document.createElement("h2");
element.innerHTML = tit[i];
$("#tit").append(element);
}
});
over here we use jQuery's .append, and we create a node and we append the node into the wrapper element.
If you have any questions, please leave a comment below and I will reply ASAP

Your best bet to keep things organised is to use a templating engine like handlebars. I've set up a jsfiddle for you that renders out your articles using the example data you provided (which needed a bit of formatting to get working).
http://jsfiddle.net/4ud6rLfq/10/
// This is what you'll need to get the data via AJAX
var source = $("#template").html();
var template = Handlebars.compile(source);
$.ajax({
type: "GET",
url: "http://localhost/again/www/index.php",
dataType: "json",
success: function (data) {
$.each(data, function(key, value) {
$('#articles').append(template(value));
});
}
});
// A demo using the data you provided (formatted a bit)
var data = [
{
"codigo":"32",
"titulo":"Some title here",
"descricao":"Here is my description",
"data":"2015-10-29 21:48:13"
},{
"codigo":"33",
"titulo":"Title here",
"descricao":"description here",
"data":"2015-10-30 20:45:46"
}
];
var source = $("#template").html();
var template = Handlebars.compile(source);
$.each(data, function(key, value) {
$('#articles').append(template(value));
});
And the HTML you'll need:
<script id="template" type="text/x-handlebars-template">
<article class="underline">
<a href="#">
<img class="incidente" src="" alt="{{titulo}}" />
</a>
<h2>{{titulo}}</h2>
<p class="desc">{{descricao}}</p>
<p></p>
<div class="date" class="date">{{data}}</div>
<img class="tick" alt="não resolvido" src="img/no-tick.png">
<img class="apoio" alt="apoiar" src="img/apoio.png">
</article>
</script>
<div id="articles"></div>
There's an example using your $.ajax function commented out and another example below it using the data variable - all you need to do is include handlebars in your page after jQuery and it should be good to go. You can edit the variables in the template to match whatever you pass back to your script via ajax.
Basically what's happening is your setting up the template for your data first, then you loop over your data and bind each item to the template, the item template is then appended to the #articles container as HTML and it moves on to the next item until it's finished.

If I understand you, you have multiple articles and you want to change their titles dynamically?
If so, first of all you should remove;
$('#tit').html(tit);
Then inside the loop put this:
$('#content article:eq('+$i+')').find('#tit').html(object.titulo);
This works only if $i is the same as the elements index relative to their parent.

You can make a function which returns a string with the html-markup. If you need to populate the html-template then you will need to send params to that function. Here is an example of the javascript:
http://jsfiddle.net/fnLjcfvr/1/
function getHtml(title){
var html = "";
html += '<div class="content">';
html += '';
html += '<article class="underline">';
html += '<a href="incidente.html"><img id="incidente"';
html += 'src="img/buraco.jpg" alt="Incidente" /></a>';
html += '<h2> + ' title ' + </h2>';
html += '<p id="desc">Esse buraco na rua Montes Claros já está há 1 ano trazendo transtornos aos moradores</p><p></p>';
html += '<div class="date" id="date"></div>';
html += '<img class="tick" alt="não resolvido" src="img/no-tick.png">';
html += '<img class="apoio" alt="apoiar" src="img/apoio.png">';
html += '';
html += '</article>';
return html;
}

Related

AngularJS append HTML in the ng-repeat element

Using AngularJS I need to append HTML to the elements of ng-repeat, using the selector: 'objectMapParent-' + post._id
<div ng-repeat="post in posts">
<div id="{{ 'objectMapParent-' + post._id }}">
<h5 style="color:blue; margin-top: 3px;">{{post.title}}</h5>
</div>
</div>
so I created a loop to loop through the elements of the posts array, where for each element I call the function: createElement
$scope.posts = [{
_id: "1",
title: "map of london"
}, {
_id: "2",
title: "map of brazil"
}, {
_id: "3",
title: "map of usa"
}];
$scope.posts.forEach(function(post) {
// console.log(post);
createElement("#objectMapParent-" + post._id, function() {
//create map here after append
});
});
This callback function gets a selector, elementParent, which we use to find the node in the DOM, and then apend the desired HTML
var createElement = function(elementParent, cb) {
var aux = elementParent;
var postId = aux.replace("#objectMapParent-", "");
var myElement = angular.element(document.querySelector(elementParent));
var html = "<div id='objectMap-" + postId + "'><div id='BasemapToggle-" + postId + "'></div></div>";
myElement.append(html);
cb();
};
But something does not work, as far as I'm concerned, the document.querySelector function can not find the selector.
It seems to me that when it tries to select, the node does not yet exist in the DOM.
I reproduced the code in the codepen, it might help.
How to Encapsulate jQuery code in a Custom Directive
Any jQuery code that manipulates the DOM should be encapsulated in a custom directive so that it is executed when the AngularJS framework ng-repeat directive instantiates the element.
<div ng-repeat="post in posts">
<div id="{{ 'objectMapParent-' + post._id }}">
<h5 style="color:blue; margin-top: 3px;">{{post.title}}</h5>
<my-element post="post"></my-element>
</div>
</div>
app.directive("myElement", function() {
return {
link: postLink,
};
function postLink(scope,elem,attrs) {
var post = scope.$eval(attrs.post);
var html = `
<div id="objectMap-${post._id}">
<div id="BasemapToggle-${post._id}">
</div>
</div>
`;
elem.append(html);
}
})
To use jQuery, simply ensure it is loaded before the angular.js file.
For more information, see
AngularJS Developer Guide - Creating Custom Directives
AngularJS angular.element API Reference

Refer to object in second column

I am trying to refer to object in second column (object link_icon) and based on .json data, I am assigning new url.
Structure of my html:
<div class="details">
<h1 id="title">title</h1>
<h3 id="author">
author
</h3>
</div>
<a href="https://www.google.pl/">
<div><i class="link_icon"></i></div>
</a>
$(function(){
var url = 'img_and_data/' + randomNumbers[bgImgIndex] +'.json';
var title = $("#title");// the id of the heading
var author = $("#author a");// id of author
var link_icon = $(".link_icon a"); // <------- problem probably is here
$.getJSON(url, function (data) {
title.text(toTitleCase(data.title));
author.text(data.copyright);
author.attr("href", data.url);
link_icon.attr("href", data.permalink);
});
}
Here is my full code:
https://jsfiddle.net/cvv0sen8/8/
How should I refer to link_icon to modify href?
Could you help me?
JSON:
{
"title": "example title",
"copyright": "example author",
"permalink": "https://www.bing.com/",
"url": "http://www.yahoo.com"
}
var link_icon = $(".link_icon a");
Your selector here means "every a tag which has a tag with class link_icon as a parent". Problem is your html document doesn't contain any a tag in link_icon: your selector will return nothing.
You may change your html like this:
<div><a class="link_a" href="#"><i class="link_icon"></i></a></div>
And your js:
var link_a = $(".link_a");
// ...
link_a.attr("href", data.permalink);

How to create <div> with several children in loop

I created a div with a class name of div class = "postWindow".
html:
<div class = "postWindow">
<div class = "userName">Initial Name</div>
<div class = "postTitle">Init title</div>
</div>
Now, what I am trying to achieve is that I can create upto 10 of these in a single html window. (upto because the amount of posts may vary from 1-10 and the amount is dynamic)
I tried using the appendChild() method but realized it only populated the div as the new element. It did not create a new postWindow
My .js file has the following function:
function createPost(){
var count = 0;
while(count < upLimit){
$.ajax({
url: root + '/posts/'+curr,
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
//im lost here
}
});
count++;
}
Using console.log my Json response is something like this
0: Object
title: "First post"
body: "This is a post"
id: 1
userId: 27
.
.
.
100: //same format of data as object 0
Any help would be appreciated! :D
Here's a simple fiddle to demonstrate the above: https://jsfiddle.net/LLceoLwg/
HTML:
<div class="container">
<div class = "postWindow">
<div class = "userName">Initial Name</div>
<div class = "postTitle">Init title</div>
</div>
</div>
jQuery:
$(document).ready(function(){
for(var i=0; i<10; i++){
$(".postWindow").parent().append("<div class='postWindow'><div class='userName'>Initial Name</div><div class='postTitle'>Init title</div></div>");
}
});

How do i loop through an ajax response and display it in html

I'm a PHP developer and i'm looking for something like a foreach loop for an ajax response
I have a card design in html and i would like the response of the ajax request make a new card for each object in the ajax response
This is my code for far
ajax:
$.ajax({
type:"GET",
url:"http//url_to_api.com/projects/v1" ,
dataType: "json",
success:function(mdata){
var result = '';
$.each(mdata, function (index, element) {
result += + element.project_name ;
console.log(element.project_name); // alert the values
});
$('.cho-card-title').html(result);
}
});
html that i want my ajax response to populate for each object in the response data
<div class="card-row">
<div class="card">
<div class="card-img">
//image.of.ajax.responce
<img src="">
</div>
<div class="card-title">
// title.of.ajax.responce
</div>
<div class="card-description">
// title.of.ajax.description
</div>
<div class="select-card">
Select
</div>
</div>
</div>
currently the code loops through the response and displays everything in one card how do I get every response in its own card.
You can create and append elements inside the .each statement.
This is untested, but something like this might work:
$.each(mdata, function (index, element) {
var div = $('<div />') // Create the div
.addClass('cho-card-title') // Add the class name
.html(element.project_name); // Insert the html
// Append the new div to whatever your container is
$('.container').append(div);
});

How to read additional data within handlebars block expression template?

My html document will have div container which gets populated with handlebars template name 'relatedVideosTemplate' on execution.
<div id="relVideos"></div>
Below anonymous function will make ajax request and pass the data to handlebar template which loops over all items in data object to construct related videos UI.
(function(options) {
var defualt = {
defaultThumb: "/url/to/default/thumbnail/",
apiURL: '/path/to/api/url'
};
options = options || {};
options = $.extend(true, defaults, options);
// handlebars template for the related video carousel
var relatedVideosTemplate : "<h3>Related Videos</h3>" +
"<ul class=\"related-videos\">" +
"{{#foreach items}}<li class=\"video {{#if $last}} last{{/if}}\">" +
"<a href=\"/video/?videoid={{id}}\" class=\"image\">" +
"<img alt=\"{{name}}\" {{#if videoStillURL}}src=\"{{videoStillURL}}\"{{else}}src=\"{{defaultVideoThumb}}\"{{/if}} width=\"90\" height=\"75\" data-id=\"{{id}}\" onerror=\"this.src='{{defaultVideoThumb}}';\" />" +
"<span class=\"video-time\">{{length}}</span></a>" +
"<div class=\"info\"><h5>{{name}}</h5>" +
"<span class=\"published-date\">{{publishedDate}}</span>" +
"{{#if playsTotal}}<span class=\"video-views\">{{playsTotal}} views</span>{{/if}}" +
"</div></li>{{/foreach}}" +
"</ul>",
template, relVideosHTML;
$.ajax({
url: options.apiURL,
success: function(data) {
template = Handlebars.compile(relatedVideosTemplate);
relVideosHTML = template(data);
$("#relVideos").html( relVideosHTML );
}
});
});
Its very likely the video still image (thumbnail) for some videos will return 404 and in that case I use onerror event on image tag to replace it with default thumbnail.
Is there a way to pass this default thumbnal value as object to handlebars block expression template ?
I don't want to amend the data object to have 'defaultThumb' property for all items. Like below...
for ( i = 0, max = data.items.length; i < max; i++) {
// Adding new property to each item in data object
data.items[i].defaultThumb = options.defaultThumb;
};
It seems to me amending data property in above loop is non efficient as the defaultThumb is same across all videos which return 404 for still(thumb) image.
Why not set defaultVideoThumb once at the top level and then reference it as {{../defaultVideoThumb}} inside the loop? Something like this in the template:
<img
{{#if videoStillURL}}src="{{videoStillURL}}"{{else}}src="{{../defaultVideoThumb}}"{{/if}}
width="90" height="75"
onerror="this.src='{{../defaultVideoThumb}}'
>
and then in the JavaScript:
data.defaultVideoThumb = '...';
var html = template(data);
Demo: http://jsfiddle.net/ambiguous/9ecx3/

Categories

Resources