samedi 28 novembre 2015

Generate number on click then pass that to another function

Say I have some text and a button:

<p id="text-box">placeholder text</p>
<button id="text-btn">New Quote Please.</button>

When I click the button I want something new to appear in the #text-box. So I create an array and some jQuery functions:

var textArr = [word0, word1, word2, word3, word4...];

$(document).ready(function() {
  $( "#text-btn" ).click(function(){
    x = Math.floor(Math.random()*textArr.length); //This line is the problem.
  });
  $("#text-box").html(textArr[x]);
});

The idea is when the button is clicked a random number is generated then that number is used to select an item in textArr to display in #text-box. I am fairly certain that the problem lays in the commented line. I think that the x value in the $("#text-btn") function is either not being created at all or is not being passed into the $("#text-box") function.

Thank you for your time.




Aucun commentaire:

Enregistrer un commentaire