Amanda Pistolato
Amanda Pistolato

Reputation: 37

JavaScript loop printing a HTML code

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><a href="basic_markup.html" id="tit"></a></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?

Upvotes: 1

Views: 8263

Answers (4)

Tim Sheehan
Tim Sheehan

Reputation: 4024

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><a href="#">{{titulo}}</a></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.

Upvotes: 1

Salmin Skenderovic
Salmin Skenderovic

Reputation: 1720

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><a href="basic_markup.html" id="tit"> + ' title ' + </a></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;
}

Upvotes: 0

Viraj Shah
Viraj Shah

Reputation: 792

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

Upvotes: 1

Rens Tillmann
Rens Tillmann

Reputation: 861

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.

Upvotes: 0

Related Questions