I’m working with JSON data and process that data to insert it into the proper html-tags. Some times the JSON data doesn’t contain information or isn’t available at all. In the given example the src is empty or the kicker isn’t there which gives results like {} or undefined or ” or null on this line:
document.getElementById("placeholder_" + (k)).src = jsonData[i].src;
I looked for a solution on the board and tried that but didn’t succeed. Or I didn’t understand the logic. Some examples that didn’t work me:
document.getElementById('id2').src = json.img2 ? json.img2.link : 'defaultLink';
Or I consulted this link:
JSON occasionally undefined – how do I check?
This is my code snippet and I want to check if jsonData[i].src
has data (an url) in it. How can I do that?
In the second part the src is empty and in the third part the kicker is missing. How to check that?
var jsonData = [
{
src: 'https://www.w3schools.com/tags/img_girl.jpg',
kicker: 'Kyiv',
headline: 'Grief and defiance in city on first anniversary of war in Ukraine',
},
{
src: '',
kicker: 'Russia',
headline: 'how can Ukraine win? And what is the feeling within Russia?',
},
{
src: 'https://www.w3schools.com/tags/img_girl.jpg',
headline: 'how can Ukraine win? And what is the feeling within Russia?',
}
]
$(document).ready(function () {
var k = 1;
//loop through json data and insert into corresponding divs
for (var i = 0; i < jsonData.length; i++) {
document.getElementById("placeholder_" + (k)).src = jsonData[i].src;
document.getElementById("placeholder_" + (k = k + 1)).innerText = jsonData[i].kicker;
document.getElementById("placeholder_" + (k = k + 1)).innerText = jsonData[i].headline;
k = k + 1;
}
});
3
Answers
OK, I think I found a solution to check if there's information in this line
Especially this part:
jsonData[i].src
You are using an assignment operator
=
instead of an equal to operator==
/===
. I suggest reading JavaScript Operators.The following should work: