Does not display user names in Jquery Alert

Asked

Viewed 165 times

2

Well I want to access the text content inside the div and show in an Alert(), but for this I have a list of users selected from the database, I made a small trick to add a counter in each class of the div that contains the user name, see the example:

and so on. Only when I put Alert(), it displays all users at once within Alert, even though I create a div for each one. Someone and give a hand. my Code:

$('.innerbox_contatos_search').click(function(){
  $('.info-part a').addClass('ativo');
  var i = 1;
  $(".ativo").each( function() {
    $(this).attr("class", "ativo-"+i); 
    alert($('a.ativo-'+i).text());
  i++;
});
});
  • 1

    You can add your HTML as well?

  • What exactly do you want to show on Alert?

  • I want it to show only the class with the increment of each div, for example when I click on David appear: David and the class of "David" will be: <div class="active-1"></div> When I click on josé (which in the case is the second user)appear: Joseph and Joseph’s class will be: <div class="active-2"></div>

3 answers

1

You don’t need the i++ to perform this operation. You do not need to counter!

The each jQuery uses the this inside the callback as the current element within the context of the loop.

See a modified example of your code:

$('.innerbox_contatos_search').click(function(){
    $('.info-part').find('a').addClass('ativo');

    $(".ativo").each(function() { 
      // this é o elemento atual do loop
      alert($(this).text())

  });
});

See working on Jsfiddle

  • Wallace, I want it to show only the class with the increment of each div, for example when I click David appear: David and the class of "David" will be: <div class="active-1"></div> When I click josé (which in the case is the second user)appear: Joseph and Joseph’s class will be: <div class="active-2"></div>

0

Below solution based on the solution given by Wallace Maxters, adding the application of the class "active-i" in the elements.

$('.innerbox_contatos_search').click(function(){
    $('.info-part').find('a').addClass('ativo');
    i=1;
    $(".ativo").each(function() { 
        $(this).addClass("ativo-"+i);
        console.log($('a.ativo-'+i).text());
        i++;
  });
});

Link working on JS Fiddle: http://jsfiddle.net/moneisa123/qxjh1ycw/4/

0

This is because you are putting the whole element into Alert. You need to use the this to access the contents of the element that was clicked. Try modifying your code to:

$('.innerbox_contatos_search').click(function(){
  $('.info-part a').addClass('ativo');
  var i = 1;
  $(".ativo").each( function() {
    var textAlert = "ativo-"+i;
    $(this).attr("class", textAlert); 
    alert($(this).text() + " " + textAlert);
    i++;
  });
});

Browser other questions tagged

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