How to browse a list using each JQUERY

Asked

Viewed 1,922 times

1

The scenario is as follows: I get a JSON array from my webservice and every time I go through, I get the information according to the index (event 1, 2, 3, etc)

My job is this::

 $(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "http://localhost:8080/SemanaEngenharia/webresources/services.evento/",
        data: "", /* redundante */
        dataType: "JSON", /* dispensa a necessidade do parse JSON */
        success: function(data) {
            $(data).each(function(index, element) {
                $(".titulosPostagens").html(data[i].titulo);
                $("#p").html(data[i].palestrante);
                $("#v").html(data[i].qtdVagas);
                $("#dataInicio").html('Inicio: ' + data[i].inicio);
                $("#dataTermino").html('Termino: ' + data[i].termino);
                $("#le").html(data[i].endereco);
                $("#d").html(data[i].descricao);
                $("#pa").html(data[i].publicoAlvo);
            });
        }
    }); // fim ajax
});

Return of the JSON:

 [{"descricao":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed nibh finibus, id placerat elit mollis. Proin dictum sed felis vitae vulputate. Nunc vitae velit feugiat, porttitor felis quis, pharetra risus. Integer id dolor sapien. Aenean ultricies, risus at lacinia blandit, leo mi tincidunt risus, at gravida nisi nisl ut dui. Donec vitae consectetur urna. Phasellus at augue vel nisl semper aliquet eu vel ante. Ut venenatis lacus id velit aliquet, ac congue neque mollis. Quisque at elit mollis arcu condimentum imperdiet.","endereco":"Laboratorio 4","idEvento":5,"inicio":"05/10","palestrante":"Profº José Marinho","qtdVagas":40,"termino":"09/10","titulo":"Palestra de Jogos"},{"descricao":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed nibh finibus, id placerat elit mollis. Proin dictum sed felis vitae vulputate. Nunc vitae velit feugiat, porttitor felis quis, pharetra risus. Integer id dolor sapien. Aenean ultricies, risus at lacinia blandit, leo mi tincidunt risus, at gravida nisi nisl ut dui. Donec vitae consectetur urna. Phasellus at augue vel nisl semper aliquet eu vel ante. Ut venenatis lacus id velit aliquet, ac congue neque mollis. Quisque at elit mollis arcu condimentum imperdiet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed","endereco":"CETEP (Sala 2) - UNIFAE","idEvento":6,"inicio":"05/10","palestrante":"Profº Mrº Tiago","qtdVagas":35,"termino":"09/10","titulo":"Startup: O que é e como começar?"},{"descricao":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed nibh finibus, id placerat elit mollis. Proin dictum sed felis vitae vulputate. Nunc vitae velit feugiat, porttitor felis quis, pharetra risus. Integer id dolor sapien. Aenean ultricies, risus at lacinia blandit, leo mi tincidunt risus, at gravida nisi nisl ut dui. Donec vitae consectetur urna. Phasellus at augue vel nisl semper aliquet eu vel ante. Ut venenatis lacus id velit aliquet, ac congue neque mollis. Quisque at elit mollis arcu condimentum imperdiet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed","endereco":"CETEP (Sala 2) - UNIFAE","idEvento":7,"inicio":"05/10","palestrante":"Mrº Rosa Elena","publicoAlvo":"Engenharia de Software e Computação","qtdVagas":35,"termino":"09/10","titulo":"Introdução ao Arduíno"}]

Already in my HTML, I have 3 fields of posts similar to the following code, and I would like to insert in each body the information of each index:

 <div id="menuPrincipal">
    <div class="**titulosPostagens**">
        null
    </div>
        <!-- pq as divs estao se ajustando de acordo com o tamanho do texto?-->
        <div id="palestrante">
            <i class="fas fa-chalkboard-teacher"></i> Palestrante: **<span class="p">null</span>**
        </div>

        <div id="vagas">
            Vagas: **<span class="v"></span>**/40 <!-- 18/20 18 decrementa a cada vaga confirmada-->
        </div>

        <div>
            **<div class="dataInicio">**
                null
            </div>

            **<div class="dataTermino">**
                null
            </div>
        </div>

        <div id="localEvento">
            <i class="fas fa-map-marker-alt"></i> **<span class='le'>null </span>**
        </div>

        <div id="publicoAlvo">
            <i class="fas fa-bullseye"></i> Público alvo: <**span class='pa'>null </span>**
        </div>

        <hr id="hrDivisorio">
        <div class="observacoesPostagens"></div>
</div>
  • PS: ignore the "[i]", it was only to illustrate

  • 1

    But what’s your problem? and post json that url http://localhost:8080/Semanaengenharia/webresources/services.event/ behind

  • 1

    Well, my webservice returns a list of JSON data, in case I would have to select by the Dice (event 0, event 1, event 2) according to the order of the database. But I would like jquery to run automatically, as if it were in a java (event[i].getName()). I saw some examples of each, but I couldn’t apply it in my example

  • The return of the JSON: https://imgur.com/UQ34rvs

  • 2

    Edit the question and put Json on it

  • edited !!!!!!!

Show 1 more comment

4 answers

2


Only trade data[i] for element

$(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "http://localhost:8080/SemanaEngenharia/webresources/services.evento/",
        data: "", /* redundante */
        dataType: "JSON", /* dispensa a necessidade do parse JSON */
        success: function(data) {
            $(data).each(function(index, element) {
                $(".titulosPostagens").html(element.titulo);
                $("#p").html(element.palestrante);
                $("#v").html(element.qtdVagas);
                $("#dataInicio").html('Inicio: ' + element.inicio);
                $("#dataTermino").html('Termino: ' + element.termino);
                $("#le").html(element.endereco);
                $("#d").html(element.descricao);
                $("#pa").html(element.publicoAlvo);
            });
        }
    }); // fim ajax
});

An example using your json

var data = [{"descricao":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed nibh finibus, id placerat elit mollis. Proin dictum sed felis vitae vulputate. Nunc vitae velit feugiat, porttitor felis quis, pharetra risus. Integer id dolor sapien. Aenean ultricies, risus at lacinia blandit, leo mi tincidunt risus, at gravida nisi nisl ut dui. Donec vitae consectetur urna. Phasellus at augue vel nisl semper aliquet eu vel ante. Ut venenatis lacus id velit aliquet, ac congue neque mollis. Quisque at elit mollis arcu condimentum imperdiet.","endereco":"Laboratorio 4","idEvento":5,"inicio":"05/10","palestrante":"Profº José Marinho","qtdVagas":40,"termino":"09/10","titulo":"Palestra de Jogos"},{"descricao":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed nibh finibus, id placerat elit mollis. Proin dictum sed felis vitae vulputate. Nunc vitae velit feugiat, porttitor felis quis, pharetra risus. Integer id dolor sapien. Aenean ultricies, risus at lacinia blandit, leo mi tincidunt risus, at gravida nisi nisl ut dui. Donec vitae consectetur urna. Phasellus at augue vel nisl semper aliquet eu vel ante. Ut venenatis lacus id velit aliquet, ac congue neque mollis. Quisque at elit mollis arcu condimentum imperdiet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed","endereco":"CETEP (Sala 2) - UNIFAE","idEvento":6,"inicio":"05/10","palestrante":"Profº Mrº Tiago","qtdVagas":35,"termino":"09/10","titulo":"Startup: O que é e como começar?"},{"descricao":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed nibh finibus, id placerat elit mollis. Proin dictum sed felis vitae vulputate. Nunc vitae velit feugiat, porttitor felis quis, pharetra risus. Integer id dolor sapien. Aenean ultricies, risus at lacinia blandit, leo mi tincidunt risus, at gravida nisi nisl ut dui. Donec vitae consectetur urna. Phasellus at augue vel nisl semper aliquet eu vel ante. Ut venenatis lacus id velit aliquet, ac congue neque mollis. Quisque at elit mollis arcu condimentum imperdiet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed","endereco":"CETEP (Sala 2) - UNIFAE","idEvento":7,"inicio":"05/10","palestrante":"Mrº Rosa Elena","publicoAlvo":"Engenharia de Software e Computação","qtdVagas":35,"termino":"09/10","titulo":"Introdução ao Arduíno"}];

$(data).each(function(index, element) {
  console.log(element.titulo);
  console.log(element.palestrante);
  console.log(element.qtdVagas);
  console.log(element.inicio);
  console.log(element.termino);
  console.log(element.endereco);
  console.log(element.descricao);
  console.log(element.publicoAlvo);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Creating new elements with your Json

var data = [{"descricao":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed nibh finibus, id placerat elit mollis. Proin dictum sed felis vitae vulputate. Nunc vitae velit feugiat, porttitor felis quis, pharetra risus. Integer id dolor sapien. Aenean ultricies, risus at lacinia blandit, leo mi tincidunt risus, at gravida nisi nisl ut dui. Donec vitae consectetur urna. Phasellus at augue vel nisl semper aliquet eu vel ante. Ut venenatis lacus id velit aliquet, ac congue neque mollis. Quisque at elit mollis arcu condimentum imperdiet.","endereco":"Laboratorio 4","idEvento":5,"inicio":"05/10","palestrante":"Profº José Marinho","qtdVagas":40,"termino":"09/10","titulo":"Palestra de Jogos"},{"descricao":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed nibh finibus, id placerat elit mollis. Proin dictum sed felis vitae vulputate. Nunc vitae velit feugiat, porttitor felis quis, pharetra risus. Integer id dolor sapien. Aenean ultricies, risus at lacinia blandit, leo mi tincidunt risus, at gravida nisi nisl ut dui. Donec vitae consectetur urna. Phasellus at augue vel nisl semper aliquet eu vel ante. Ut venenatis lacus id velit aliquet, ac congue neque mollis. Quisque at elit mollis arcu condimentum imperdiet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed","endereco":"CETEP (Sala 2) - UNIFAE","idEvento":6,"inicio":"05/10","palestrante":"Profº Mrº Tiago","qtdVagas":35,"termino":"09/10","titulo":"Startup: O que é e como começar?"},{"descricao":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed nibh finibus, id placerat elit mollis. Proin dictum sed felis vitae vulputate. Nunc vitae velit feugiat, porttitor felis quis, pharetra risus. Integer id dolor sapien. Aenean ultricies, risus at lacinia blandit, leo mi tincidunt risus, at gravida nisi nisl ut dui. Donec vitae consectetur urna. Phasellus at augue vel nisl semper aliquet eu vel ante. Ut venenatis lacus id velit aliquet, ac congue neque mollis. Quisque at elit mollis arcu condimentum imperdiet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tristique ligula sed","endereco":"CETEP (Sala 2) - UNIFAE","idEvento":7,"inicio":"05/10","palestrante":"Mrº Rosa Elena","publicoAlvo":"Engenharia de Software e Computação","qtdVagas":35,"termino":"09/10","titulo":"Introdução ao Arduíno"}];

//Cria um clone do elemento original
var elementoPai = $(".pai").clone();

//Removo o elemento original
$(".pai").remove();
 
//Pecorro os dados
$(data).each(function(index, element) {	  

  //Coloco as informações no elemento, estou usando class, já que ids não podem se repetir
  elementoPai.find(".titulosPostagens").html(element.titulo);
  elementoPai.find(".p").html(element.palestrante);
  elementoPai.find(".v").html(element.qtdVagas);
  elementoPai.find(".dataInicio").html('Inicio: ' + element.inicio);
  elementoPai.find(".dataTermino").html('Termino: ' + element.termino);
  elementoPai.find(".le").html(element.endereco);
  elementoPai.find(".d").html(element.descricao);
  elementoPai.find(".pa").html(element.publicoAlvo);
  
  //Cria o novo elmento, lembresse de usar clone para criar um novo e não move.
  $('.conteudo').append(elementoPai.clone());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="conteudo">
  <div class="pai">
    <p class="titulosPostagens">

    </p>
    <p class="p">

    </p>
    <p class="v">

    </p>
    <p class="dataInicio">

    </p>
    <p class="dataTermino">

    </p>
    <p class="le">

    </p>
    <p class="d">

    </p>
  </div>
</div>

  • Wictor, it worked :o. But in this case, I am setting the information in my html, and instead of getting each div with a respective index, all got the last element of the list (as was to be expected, since I use the same classes in all Divs), you know how I can get around this problem? If I have to, I’ll html it too

  • You want to create new elements on the screen, that’s it?

  • let’s assume that I have a list with 3 elements in my HTML: 1, 2, and 3, and in my JSON array I have 3 elements: A, B and C. I want each "each" to set the information according to the index, getting: 1 A 2 B 3 C it’s all like this: 1 C 2 C 3 C I’m sorry for explaining, forgive me

  • I made an example using your json.

  • 1

    Dude, Voce is magnificent, I can’t believe it worked kk. THANK YOU!

1

You don’t need to use jQuery to iterate in your array, you can use the method Array.forEach.

let lista = ['a', 'b', 'c'];

lista.forEach(function(element, index) {
  console.log(`lista[${index}] == ${element}`);
});

But if you really make a point of using jQuery for this you should use the variation jQuery.each().

let lista = ['a', 'b', 'c'];

$.each(lista, function(index, element) {
  console.log(`lista[${index}] == ${element}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


The difference between $.each() and $(seletor).each() is that the second iterates exclusively on jQuery type objects, while the first acts as a "static method" functioning as a generic iterator.

And as for compatibility, the Array.forEach() already have a decent compatibility (IE9+)

0

A not so "pretty" solution, so to speak, would be to scan the object and pick up the "array" according to its key. Suppose your object is like this: {"array":[{obj_key1:value_1...},{obj_key2:value_2...},{obj_key3:value_3...},.. ,{obj_keyN:value_N...}]}. With this I get the value that has array as key:

Object.keys(data).forEach(function(key){
      if(key=="array"){
           var list=data[key]; // agora list é seu array de objetos, só iterar sobre ele para percorrer todos objetos dentro dele 
      }
 }

0

When I need to make one foreach in a objeto I use a code similar to this, below.

The Method hasOwnProperty prevents me from accessing object properties.

function each(e,callback){ 
    for(var i in e){ 
        if( e.hasOwnProperty(i) ) 
            callback.call(e,i,e[i]); 
    } 
}



each( [1,2,3,4,5,6] , console.log );

each( {"key1":1234,"key2":2,"key3":4}, console.log );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.