I have an array
firstArray = [ "Blue", "Red", "Green" ];
Red
I want to click a button and display a random result from that array, let's say it's "Red". Then based on that result "Red" I want to click a second button and get another random result from another array.
blueArray = [ "Sky", "Water", "Jeans" ];
redArray = [ "Apple", "Firetruck", "Rose" ];
greenArray = [ "Grass", "Money", "Leaves" ];
Red - Rose
Then I want to click the first button again, get a new result and clear the second button's result.
You can group the three arrays in an object whose keys will be in the first array:
var colors = [ "Blue", "Red", "Green" ]; // colors (keys from items object)
var items = { // each color from colors has an array of items in this object
"Blue": ["Sky", "Water", "Jeans"], // items for color "Blue"
"Red": ["Apple", "Firetruck", "Rose"], // ...
"Green": ["Grass", "Money", "Leaves"] // ...
};
var color = null; // should be here in the outside so it will be accessed by both event listeners (you can initialize it to a color if you want)
$("#first-button").click(function() { // when clicking the first button ...
color = colors[Math.floor(Math.random() * colors.length)]; // ... choose a random color from colors and assign it to the variable color
$("#color-span").text(color); // set the text of the color span
});
$("#second-button").click(function() { // when clicking the second button ...
if(color) { // check if we had chosen a color (using the first button)
var item = items[color][Math.floor(Math.random() * items[color].length)]; // then choose an item from the equivalent array (if color is "Blue" then items.Blue will be chosen)
$("#sentence-span").text(color + " " + item); // set the text of the sentence span (using both color and item
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="first-button">First Button</button>
<button id="second-button">Second Button</button>
<p><b>Color is: </b><span id="color-span"></span></p>
<p><b>Sentence is: </b><span id="sentence-span"></span></p>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments