I have ruby text that fetches a random row from a SQL database of quotes,
and later I use javascript to display this random quote on button click:
My issue is that I would like to generate a NEW random quote whenever the button is pressed. I have been told I can do this using jQuery, but I've very lost as to how to go about this.
In a controller:
random_offset = rand(Quote.count - 1)
@random_quote = Quote.offset(random_offset).first
Javascript:
var generatedQuote = '"<%= @random_quote.quote %>" <br> - <%= @random_quote.author %>'
function populateQuote(){
$("#quoteArea").val(generatedQuote);
$("#imagewrap h3").html(generatedQuote);
}
var quoteButton = document.getElementById('randomQuote');
quoteButton.addEventListener('click', function (){
populateQuote();
});
You should render all the quotes and randomize clientside. Javascript :
var quotes = <%= raw Quote.all.map {|q| [q.quote, q.author]}.to_json %>;
var random_quote = function(){
var quote_item = quotes[Math.floor(Math.random()*quotes.length)];
return '"'+quote_item[0]+'" <br> - '+quote_item[1];
};
$("#randomQuote").click(function(){
var new_random_quote= random_quote();
$("#quoteArea").val(new_random_quote);
$("#imagewrap h3").html(new_random_quote);
});
Or you should fetch the server with each click on the button, depending on the number of quotes available / what you prefer for your web app.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.