Muhamad Yulianto
Muhamad Yulianto

Reputation: 1663

JSON Display just one data using javascript

I have this json, and i want to display just "cat_news" in my html5 using javascript,

[
{
    "id_news": "3",
    "cat_news": "Category Three",
    "title": "News Content next",
    "content": "testingg\nThis is some content\nwith long post\n",
    "media": "7e3e9-komodo.jpg",
    "message": "Broadcast message news 3"
}
{
    "id_news": "4",
    "cat_news": "Category Three",
    "title": "News Content next",
    "content": "testingg\nThis is some content\nwith long post\n",
    "media": "7e3e9-komodo.jpg",
    "message": "Broadcast message news 3"
}
]

but when i use my script :

$(data).each(function() {
var title = "<h3 class='title-a'>"+ this.cat_news + "</h3>";
$('#title').append(title);
});

it display repeated (more than one result). Can you help me to display it just one result?

Thanks

Upvotes: 0

Views: 88

Answers (4)

Jack
Jack

Reputation: 1769

Your function runs twice, i.e. for element 0 and 1 of your array. This produces two h3 tags in your #title. If this is not the intended behaviour, you can access the array objects directly using something like this: data[index].cat_news, where index is the array's index, starting from 0 (in your case 0, 1).

If you want the cat_news of the last element, just use data[data.length - 1].cat_news.

Upvotes: 1

R4nc1d
R4nc1d

Reputation: 3113

Check this Fiddle

$(data).each(function() {
    var title = "<h3 class='title-a'>"+ this.cat_news + "</h3>";
    $('#title').html(title);
});

Instead of append use html

I would however suggest that you maybe change your JSON so that you don't have the cat_news in both objects

Upvotes: 0

Marin Takanov
Marin Takanov

Reputation: 1138

Try like that:

$(data).each(function(index) {
var title = "<h3 class='title-a'>"+ data[index].cat_news + "</h3>";
$('#title').append(title);
});


Also, you are missing a "," between the objects in the data array.

Upvotes: 1

talalUcef
talalUcef

Reputation: 124

If you want to display just one element don't use a loop, just get the element from json data or pass an id or a filter to the function to return just one

Upvotes: 0

Related Questions