I'm looking at creating a theme Randomizer by having menu dropdowns of categories. Each category has an associated array of items. For example, I've got an array full of mammals, and if a user chooses Mammal from the drop-down, they get a random mammal from the mammal array.
I can do it with a bunch of if statements, checking if a value is mammal, use the mammal array. The problem is there will be a lot of categories/arrays. So I'm trying to find a way to get the value, and then grab the array with the same name.
Here is the working code just using if statements:
<form class="firstItem">
<select name="firstName" id="firstName">
<option value="animals">---Animals---</option>
<option value="mammals">Mammals</option>
<option value="insects">Insects</option>
<option value="birds">Birds</option>
<option value="reptiles">Reptiles</option>
<option value="fish">Fish/Aquatic</option>
<option value="prehistoric">Prehistoric</option>
</select>
</form>
<button class="button" id="submitBtn" onclick="submit()">Submit</button>
<div class="results">
<p id="resultsp"></p>
</div>
<script>
var mammals = ["Cow", "Horse", "Pig", "Donkey", "Elephant"];
var insects = ["Weevil", "Hercules Beetle", "Ladybug", "Tarantula", "Moth"];
function submit() {
var firstName = document.getElementById("firstName");
var firstTemp = firstName.value;
var whatVar;
if (firstTemp == "mammals") {
whatVar = mammals.slice(0);
} else if (firstTemp == "insects") {
whatVar = insects.slice(0);
}
random_items(whatVar);
var resultsp = document.getElementById("resultsp");
resultsp.innerText = random_items(whatVar);
function random_items(firstName)
{
return whatVar[Math.floor(Math.random()*whatVar.length)];
}
}
</script>
I'd like to replace all the if statements with something that says whatever the value of firstName is, grab that variable.
I've tried replacing all the if statements with:
var whatVar = firstTemp;
but as firstTemp is a value, it treats it like a String, so if mammals is chosen it'll spit out one letter of the word mammals, rather than an item from the mammals array.
Am I going about this in a completely wrong way?