0

I have an array in a JSON file and what I want to do is pull a single entry from the array and display it when the page loads. I have gotten partway there using this question and answer, however my attempt to adapt this answer causes the output html block to repeat the array items in sequence instead of simply picking one.

Here is a screenshot of what I get: screenshot of output

I am likely doing something real stupid, and I hope someone can point this out. My script is as follows:

    $.getJSON('recommend.json', function(data) {
    var entry = data[Math.floor(Math.random()*data.length)];

$.each(data, function(entryIndex, entry) {
        var html = '<div class="rec_img"><img src="./recs/' + entry['img'] + '" /></div>'; 
    html += '<span class="rec_title">' + entry['title'] + '</span><p>';
        html += '<span class="rec_author">' + entry['author'] + '</span><p>';
        html += '<span class="rec_blurb">' + entry['blurb']  + '</span>';

        $('#recblock').append(html).fadeIn();
      });
    });

Any questions just let me know.

Community
  • 1
  • 1
  • "causes the output html block to repeat the array items in sequence". Do you expect $.each() to do something other than exactly that? If you just want a single item, remove the $.each() and it will only do it one time. You also have 2 open

    tags with no

    . Could be causing issues
    – mhodges Jul 25 '16 at 21:12
  • 1
    As mentioned, "I am likely doing something real stupid" - I composed my code block from another unfinished Q+A, and I didn't know **what** $.each does! I'll look at this as a solution though! – Elliotpage Jul 26 '16 at 08:45

1 Answers1

3

Cut this:

$.each(data, function(entryIndex, entry) {

The whole purpose of $.each is to iterate over the entire array, which is the opposite of what you want. You're already defining entry earlier as a random entry from the data.

So you'll have:

$.getJSON('recommend.json', function(data) {
    var entry = data[Math.floor(Math.random()*data.length)];

    var html = '<div class="rec_img"><img src="./recs/' + entry['img'] + '" /></div>'; 
    html += '<span class="rec_title">' + entry['title'] + '</span><p>';
    html += '<span class="rec_author">' + entry['author'] + '</span><p>';
    html += '<span class="rec_blurb">' + entry['blurb']  + '</span>';

    $('#recblock').append(html).fadeIn();
});
VoteyDisciple
  • 37,319
  • 5
  • 97
  • 97
  • Okay, great, thanks. As mentioned, "I am likely doing something real stupid" and did not know what $.each does. I'll plug this in and give it a go. – Elliotpage Jul 26 '16 at 08:46