tags:

views:

54

answers:

2

Hi,

I have this jquery code to output the entries in a JSON file on page load...

$.getJSON('b.json', function(data) { $('#dictionary').empty().hide();

      $.each(data, function(entryIndex, entry) {
        var html = '<div class="entry">';
        html += '<h3 class="title">' + entry['title'] + '</h3>';
        html += '<div class="link_url">' + entry['link_url'] + '</div>';
        html += '<div class="image_src">';
        html += entry['image_src'];
        if (entry['quote']) {
          html += '<div class="quote">';
          $.each(entry['quote'], function(lineIndex, line) {
            html += '<div class="quote-line">' + line + '</div>';
          });
          if (entry['author']) {
            html += '<div class="quote-author">' + entry['author'] + '</div>';
          }
          html += '</div>';
        }
        html += '</div>';
        html += '</div>';

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

What I need to do is load one of these entries, randomly.

Any advice appreciated.

Many thanks, C

The JSON file is... [ { "title": "WESITE NAME", "link_url": "http://www.website.com", "image_src": "http://www.website.com/images/recent.jpg", }, { "title": "WESITE NAME", "link_url": "http://www.website.com", "image_src": "http://www.website.com/images/recent.jpg", }, { "title": "WESITE NAME", "link_url": "http://www.website.com", "image_src": "http://www.website.com/images/recent.jpg", } ]

+1  A: 
$.getJSON('b.json', function(data) { 
  var entry = data[Math.floor(Math.random()*data.length)];
  //do the same exact thing with entry
}
Alex Bagnolini
When I alert() the entry variable I get [object Object]
Model Reject
That is because alert can't handle arrays or objects. Try using the Firefox plugin Firebug and do a console.log();
PetersenDidIt
Try `alert(entry.title);`, where title is a property of the JSON object returned.
Alex Bagnolini
A: 

Looks like you want a random entry from an array.

try:

var random_entry = entry[Math.floor(Math.random() * entry.length)]
David