Hi, looking at this example of Plunker:
http://plnkr.co/edit/z0bnxjV2XkBZC0yJxL7Z?p=preview
can some one please tell my why does each answer and each question coming from the JSON file show twice?
Thanks
Printable View
Hi, looking at this example of Plunker:
http://plnkr.co/edit/z0bnxjV2XkBZC0yJxL7Z?p=preview
can some one please tell my why does each answer and each question coming from the JSON file show twice?
Thanks
I clicked on the link in your post and there's nothing there. Well it has a script with no code in it, no JSON file, and an HTML file that says only "Hello Plunker!"
But to try answering the question, I would guess that either you're fetching the JSON twice or have things listed twice in it. Or possible you're iterating over the retrieved JSON object twice.
Sorry, I just updated the link. Now it works.
OK, what you're doing is iterating over the array , and each item (each i) gets gone over twice, once for each key. Change:
to:Code:var result = '';
for (var i = 0; i <= data.length; i++) {
for (var key in data[i]) {
result += '<select class="my-select"><option>' + data[i].question + '</option></select>';
result += '<div class="my-div">' + data[i].answer + '</div>';
}
}
If you want to iterate both the array and its contained objects, this would work:Code:var result = '';
for (var i = 0; i < data.length; i++) {
result += '<select class="my-select"><option>' + data[i].question + '</option></select>';
result += '<div class="my-div">' + data[i].answer + '</div>';
}
Code:$(document).ready(function() {
$.getJSON('faq.json', function(data){
var tags = ['<select class="my-select"><option>', '</option></select>', '<div class="my-div">', '</div>'],
result = [], i = data.length, c = -1, t = tags.length;
while (--i > -1) {
for(var key in data[i]){
result.push(tags[++c % t] + data[i][key] + tags[++c % t]);
}
}
document.getElementById('container').innerHTML = result.join('\n');
}); //getJSON
// $('.my-select').on('click', function(e) {
// $(this).next(".my-div").slideToggle();
// });
}); // ready