SmalliSax
SmalliSax

Reputation: 342

jQuery click event to display specific data inside JSON array not working properly

I have created 3 dummy users with JSON array like this:

var userArray = {"users":[
    {"Name":"User1","Email":"[email protected]"},
    {"Name":"User2","Email":"[email protected]"},
    {"Name":"User3","Email":"[email protected]"}
]};

Now, I want to display only the name of each user stored inside a div that has a class.

var i = 0
document.writeln("<div id=tableThis>");
for(i=0;i<userArray.users.length;i++)
{
    document.writeln("<div class=allUser>");
    document.writeln("<b>User :: </b>"
            + userArray.users[i].Name);
    document.writeln("<div class=emails><b>Email :: </b>"
            + userArray.users[i].Email  +"</div>");
    document.writeln("</div>");
}

It works fine to display only the names if I give the class .emails display:none

Now, what I am trying to achieve is when each name is clicked, it should display their e-mails below in a div. But everytime I click the div called .allUser it will display all the emails right away, which makes sense because all of the emails have the same class.

I am using the code below

$(document).ready(function(){
$(".allUser").click(function() {
    $('.emails').show(1000);
});

});

I would preferably want to toggle each name so I could show, hide each users email when you click the name of each user.

It´s hard for me to provide a fiddle when they dont allow document.writeIn

Would there be a neater/cleaner way to achieve this small task ?

Upvotes: 0

Views: 526

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You need deleagted event as html is generated dynamically after DOM load, and use find() to get Child element with class .emails,

Do like this:

$(document).ready(function(){
$(document).on("click",".allUser",function() {
    $(this),find('.emails').show(1000);
});

});

Upvotes: 1

Related Questions