David Lett David Lett - 1 month ago 6
jQuery Question

Set HTML elements to random object key:value pairs

I'm trying to use the "database" I have made to cycle through some the quotes at random when the button is clicked and changing the existing quote in the HTML to the random quote and the existing author in the same way

var myDatabase = [
{quote:"I have learned silence from the talkative...", author:"Khalil Gibran"},
{quote: "One of the blessings of old friends that you can afford to be stupid with them." author:"Ralph Waldo Emmerson"},
{quote: "Once we accept our limits, we go beyond them." author:"Albert Einstein"}
];
var newQuote = document.getElementById('displayedQuote');
var newAuthor = document.getElementById('author');

$("#quoteButton").click(function() {
var rand = Math.floor(Math.random()*database.length)
newQuote = myDatabase.[rand].quote;
newAuthor = myDatabase.[rand].author;
});

Answer

Firstly your "Database" has syntax errors. It should read:

var myDatabase = [{
  "quote": "I have learned silence from the talkative...",
  "author": "Khalil Gibran"
}, {
  "quote": "One of the blessings of old friends that you can afford to be stupid with them.",
  "author": "Ralph Waldo Emmerson"
}, {
  "quote": "Once we accept our limits, we go beyond them.",
  "author": "Albert Einstein"
}];

Secondly, you're mixing vanilla JS with Jquery. Whilst this isn't technically wrong it's much easier to read if you just stick to one or the other

var newQuote = $('#displayedQuote');
var newAuthor = $('#newAuthor');

Lastly, the syntax in your click method is incorrect. You're assigning a value to the newQuote and newAuthor variables rather than manipulating the element. What you want to do is use the .text() method to add the object values to the DOM.

Also, you don't need the dot notation before the [rand] integer and you want myDatabase.length not database.length

$("#quoteButton").click(function() {
    var rand = Math.floor(Math.random() * myDatabase.length)
    newQuote.text(myDatabase[rand].quote) 
    newAuthor.text(myDatabase[rand].author)
});

Here's a working example: https://codepen.io/mark_c/pen/pExxQA