Home > Enterprise >  How can I generate a random selection based on user's <select> option choice?
How can I generate a random selection based on user's <select> option choice?

Time:11-24

I am trying to have a user select a genre from my drop down list and get a random result from the genre they selected that is then displayed on the screen.

In other words, my idea is to have a user get a random options from the genre they choose from my list.

I am very very new to JavaScript but I want to try to do something creative for my project. I have tried this so far

function xyz() {
  var x = document.getElementById("selectedId").value;
  if (x == "action") {
    var action = ["Attack on Titan", "Fullmetal Alchimist", "One Punch Man", "Sword Art Online", "My Hero Academia", "Demond Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "Code Geass", "Jujutsu Kaisen", "One Piece", "Noragami", "Akame ga Kill!", "Mob Psycho 100", "Assassination Classroom", "Blue Exorcist", "Bleach", "Parastyle", "Cowboy Bebop", "Fairy Tail", "Soul Eater", "Jojo's Bizarre Adventure", "Black Clover", "Fullmetal Alchemist", "That Time I got Reincarnated as a Slime", "Fire Force", "Balck butler", "Spy x Family", "The Seven Deadly Sins", "Tokyo Revengers", "Devilman: Crybaby", "Chainsaw Man"]
    var result = Math.floor(Math.random() * action.length);
    console.log(action);
  } else if (x == "comedy ") {
    var comedy = ["One Punch Man", "No Game NO Life", "Mob Psycho 100", "Assassination Classroom", "KonoSuba: God's Blessing on This Wonderful World!", "Kill la Kill", "Rascal Does Not Dream of Bunny Girl Senpai", "Dr.Stone", "Kaguya-sama: Love is War", "Soul Eater", "Gurren Lagann", "The Devil is a Part-Timer", "Black Clover", "High School DxD", "That Time I Got Reincarnated as a Slime", "Maid Sama!", "Spy x Family", "Black Butler", "Nisekoi", "Ouran High School Host Club", "My Little Monster", "JoJo's Bizarre Adventure:", "K-On!", "The Disastrous Life of Saiki K.", "My Teen Romantic Comedy SNAFU TOO!", "Golden Time", "Monthly Girls' Nozaki-kun", "Rent-a-Girlfriend", "The Quintessential Quintuplets", "Don't Toy with Me, Miss Nagatoro", "How Not to Summon a Demon Lord", "Ghost Stories"]
    var result = Math.floor(Math.random() * comedy.length);
    console.log(comedy);
  } else if (x == "drama") {
    var drama = ["Attack on Titan", "Fullmetal Alchemist", "Your Name.", "Steins:Gate", "A Silent Voice", "Code Geass", "Toradora!", "Your Lie in Apirl", "Re:Zero", "Angel Beats!", "Death Parade", "Violet Evergarden", "Rascal Does Not Dream of Bunny Girl Senpai", "Anohana: The Flower We Saw That Day", "Clannad", "Charlotte", "Kakegurui", "Made in Abyss", "The Pet Girl of Sakurasou", "Guilty Crown", "Jojo's Bizarren Adventure", "Classroom of the Elite", "Tokyo Revengers", "ReLIFE", "Monster", "5 Centimeters Per Second", "Plasic Memories", "Tower of God", "The Garden of Words", "Banana Fish", "Orange", "To Your Eternity", "Fruits Basket", "91 Days"]
    var result = Math.floor(Math.random() * drama.length);
    console.log(drama);
  } else if (x == "sliceofLife") {
    var sliceofLife = ["Violet Evergarden", "Anohana: The Flower We Saw That Day", "Hyouka", "Miss Kobayashi's Dragon Maid", "ReLIFE", "5 Centimeters Per Second", "The Melancholy of Haruhi Suzumiya", "Blue Spring Ride", "Kimi ni Todoke: From Me to You", "I Want To Eat Your Pancreas", "My Dress-Up Darling", "The Garden of Words", "Beastars", "Mushu-Shi", "Wolf Children", "Nana", "Barakamon", "Natsume's Book of Friends", "Bunny Drop", "Laid-Back Camp", "Love-Live!", "Tanaka-Kun is Always Listless", "Kimi ni Todoke", "School-Live!", "Tamako Market", "Beck", "Place to Place", "One Week Friends", "Girls' Last Tour", "Remake Our Life!", "Silver Spoon", "Flying Witch", "Doukyusei-Classmates", "Colorful"]
    var result = Math.floor(Math.random() * sliceofLife.length);
    console.log(sliceofLife);
  } else if (x == "fantasy") {
    var fantasy = ["Sword Art Online", "Demon Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "No Game No Life", "Jujutsu Kaisen", "One Piece", "Noragami", "Re:Zero", "Akame ga Kill!", "The Seven Deadly Sins", "Bleach", "Blue Exorcist", "Fairy Tale", "Violet Evergrden", "Soul Eater", "The Devil is a Part-Timer!", "Black Clover", "Overlord", "The Rising of the Shield Hero", "Is it Wrong to Try to Pick Up Girls in a Dungeon", "fate/Zero", "Noragami Aragoto", "Demond Slayer", "That Time I Got Reincarnated as a Slime", "log Horizon", "Re:Zero", "Goblin Slayer", "Tenki no Ko", "Tower of God", "The God of High School", "GATE", "Fruits Basket", "The Asterisk War"]
    var result = Math.floor(Math.random() * fantasy.length);
    console.log(fantasy);
  } else if (x == "horror") {
    var horror = ["Tokyo Ghoul", "Parasyte", "Another", "Elfen Lied", "Highschool of the Dead", "Deadman Wonderland", "Devilman: Crybaby", "Hellsling Ultimate", "Akira", "When They Cry", "Kabaneri of the Iron Fortress", "From the New World", "Beserk", "Shiki", "Ajin", "Psprika", "Dorohedoro", "Mieruko-chan", "Blood ", "Corpse Party: Tortured Souls", "Hell Girl", "Gantz", "Danganronpa", "Mononoke", "High-Rise Invasion", "Happy Sugar Life", "Ghost Hunt", "The Los Village", "Pupa", "Ghost Stories", "Lunar Ledgen Tsukihime", "Junji Ito Collection", "Zetman", "Memories"]
    var result = Math.floor(Math.random() * horror.length);
    console.log(horror);
  } else if (x == "mystery") {
    var mystery = ["Earsed", "The Promised Neverland", "Another", "Kakegutui", "Durarara", "Hyouka", "Made in Abyss", "Bungo Stray Dog", "Black Butler", "Monster", "Darker then Black", "Black Bullet", "Tower of God", "When They Cry", "K", "From the New World", "Serial Experiments Lain", "Great Pretender", "Vanpire Knight", "Eden of The East", "No.6", "Summer Time Rendering", "Wolf's Rain", "Amnesia", "High-Rise Invation", "Astra Lost in Space"]
    var result = Math.floor(Math.random() * mystery.length);
    console.log(mystery);
  } else if (x == "psychological") {
    var psychological = ["Deaht Note", "Tokyo Ghoul", "Re:Zero", "Erased", "The Future Diary", "The Promised Neverland", "Psycho-Pass", "Terror in Resonance", "Classroom of the Elite", "Btooom!", "FLCL", "Perfect Blue", "Ergo Proxy", "The Fruit of Grisaia", "Shiki", "Blast of Tempest", "Paranoia Agent", "Cyberpunk: Edgerunners", "Moriarty the Patriot", "Platinum Emd", "B: The Beginning", "Invaded", "When Marnie Was There", "Tomodachi Game", "Haibane Renmei", "Death Billards", "Flowers of Evil"];
    var result = Math.floor(Math.random() * psychological.length);
    console.log(psychological);
  } else {
    var boysLove = ["Given", "No.6", "Love Stage!", "Beyond the Boundary: I'll Be Here - Future", "Junjou Romantica", "Doukyusei -Classmates-", "Hitorijimd My Hero", "Sasaki and Miyano", "Dakaretai Otoko 1-i ni Odosarete Imasu.", "Super Lovers", "Yarchin Bitch-bu", "Gakuen Heaven", "kirepapa", "Yes, No, or Maybe?", "Ten Count", "Fake"]
    var result = Math.floor(Math.random() * boysLove.length);
    console.log(boysLove);
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <!--Language encoding-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0>" <title> Final Project
  </title>
  <link rel="stylesheet" type="text/css" href="FPCSS.css" />
</head>

<body >

  <div id="Top">
    <p > Anime for All
      <IMG  SRC="five.gif"> </p>
    <p>
      <br>
    </p>

    <div >
      <!-- Website navigation-->
      <h1>Directory</h1>
      <p><a href="FP1.html"> Homepage</a></p>
      <p><a href="FP2.html"> Anime History</a></p>
      <p><a href="FP3.html"> Misconceptions and Genres</a></p>
      <p><a href="FP4.html"> Recommendations</a></p>
      <p><a href="FP5.html"> Random Anime Generator</a></p>
      <p><a href="mailto:[email protected]">Email me!</a></p>
    </div>

    <div >
      <!--MS= format for main section-->
      <h1>Random Anime Generator</h1>
      <label> Select your Favorite genres to generate a anime!</label>
      <select id="selectedId">
        <option>Choose a Genre</option>
        <option value="action"> Action</option>
        <option value="adventure">Adventure</option>
        <option value="comedy">Comedy</option>
        <option value="drama">Drama</option>
        <option value="sliceOfLife">Slice Of Life</option>
        <option value="fantsy">Fantsy</option>
        <option value="horror">Horror</option>
        <option value="mystery">Mystery</option>
        <option value="psychological">Psychological</option>
      </select>
      <p> Your random anime based on chosen genre is....</p>
      <p id="result"> </p>
      <script src="Final_Project_JS.js"></script>
    </div>
  </div>

CodePudding user response:

You could store all full list of anime titles in a variable—preferably an object of arrays. Whenever user selects a genre, you could simply generate a random integer per each sublist's length and show the result in the target p element.

See the snippet below for working example. I didn't modify the original HTML markup too much, except removing irrelevant elements to the question.

For this to work as intended, you need to make sure the list of option values match the keys of titles object.

const titles = {
  action: ["Attack on Titan", "Fullmetal Alchimist", "One Punch Man", "Sword Art Online", "My Hero Academia", "Demond Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "Code Geass", "Jujutsu Kaisen", "One Piece", "Noragami", "Akame ga Kill!", "Mob Psycho 100", "Assassination Classroom", "Blue Exorcist", "Bleach", "Parastyle", "Cowboy Bebop", "Fairy Tail", "Soul Eater", "Jojo's Bizarre Adventure", "Black Clover", "Fullmetal Alchemist", "That Time I got Reincarnated as a Slime", "Fire Force", "Balck butler", "Spy x Family", "The Seven Deadly Sins", "Tokyo Revengers", "Devilman: Crybaby", "Chainsaw Man"],
  comedy: ["One Punch Man", "No Game NO Life", "Mob Psycho 100", "Assassination Classroom", "KonoSuba: God's Blessing on This Wonderful World!", "Kill la Kill", "Rascal Does Not Dream of Bunny Girl Senpai", "Dr.Stone", "Kaguya-sama: Love is War", "Soul Eater", "Gurren Lagann", "The Devil is a Part-Timer", "Black Clover", "High School DxD", "That Time I Got Reincarnated as a Slime", "Maid Sama!", "Spy x Family", "Black Butler", "Nisekoi", "Ouran High School Host Club", "My Little Monster", "JoJo's Bizarre Adventure:", "K-On!", "The Disastrous Life of Saiki K.", "My Teen Romantic Comedy SNAFU TOO!", "Golden Time", "Monthly Girls' Nozaki-kun", "Rent-a-Girlfriend", "The Quintessential Quintuplets", "Don't Toy with Me, Miss Nagatoro", "How Not to Summon a Demon Lord", "Ghost Stories"],
  drama: ["Attack on Titan", "Fullmetal Alchemist", "Your Name.", "Steins:Gate", "A Silent Voice", "Code Geass", "Toradora!", "Your Lie in Apirl", "Re:Zero", "Angel Beats!", "Death Parade", "Violet Evergarden", "Rascal Does Not Dream of Bunny Girl Senpai", "Anohana: The Flower We Saw That Day", "Clannad", "Charlotte", "Kakegurui", "Made in Abyss", "The Pet Girl of Sakurasou", "Guilty Crown", "Jojo's Bizarren Adventure", "Classroom of the Elite", "Tokyo Revengers", "ReLIFE", "Monster", "5 Centimeters Per Second", "Plasic Memories", "Tower of God", "The Garden of Words", "Banana Fish", "Orange", "To Your Eternity", "Fruits Basket", "91 Days"],
  sliceOfLife: ["Violet Evergarden", "Anohana: The Flower We Saw That Day", "Hyouka", "Miss Kobayashi's Dragon Maid", "ReLIFE", "5 Centimeters Per Second", "The Melancholy of Haruhi Suzumiya", "Blue Spring Ride", "Kimi ni Todoke: From Me to You", "I Want To Eat Your Pancreas", "My Dress-Up Darling", "The Garden of Words", "Beastars", "Mushu-Shi", "Wolf Children", "Nana", "Barakamon", "Natsume's Book of Friends", "Bunny Drop", "Laid-Back Camp", "Love-Live!", "Tanaka-Kun is Always Listless", "Kimi ni Todoke", "School-Live!", "Tamako Market", "Beck", "Place to Place", "One Week Friends", "Girls' Last Tour", "Remake Our Life!", "Silver Spoon", "Flying Witch", "Doukyusei-Classmates", "Colorful"],
  fantasy: ["Sword Art Online", "Demon Slayer", "Naruto", "Tokyo Ghoul", "Hunter x Hunter", "No Game No Life", "Jujutsu Kaisen", "One Piece", "Noragami", "Re:Zero", "Akame ga Kill!", "The Seven Deadly Sins", "Bleach", "Blue Exorcist", "Fairy Tale", "Violet Evergrden", "Soul Eater", "The Devil is a Part-Timer!", "Black Clover", "Overlord", "The Rising of the Shield Hero", "Is it Wrong to Try to Pick Up Girls in a Dungeon", "fate/Zero", "Noragami Aragoto", "Demond Slayer", "That Time I Got Reincarnated as a Slime", "log Horizon", "Re:Zero", "Goblin Slayer", "Tenki no Ko", "Tower of God", "The God of High School", "GATE", "Fruits Basket", "The Asterisk War"],
  horror: ["Tokyo Ghoul", "Parasyte", "Another", "Elfen Lied", "Highschool of the Dead", "Deadman Wonderland", "Devilman: Crybaby", "Hellsling Ultimate", "Akira", "When They Cry", "Kabaneri of the Iron Fortress", "From the New World", "Beserk", "Shiki", "Ajin", "Psprika", "Dorohedoro", "Mieruko-chan", "Blood ", "Corpse Party: Tortured Souls", "Hell Girl", "Gantz", "Danganronpa", "Mononoke", "High-Rise Invasion", "Happy Sugar Life", "Ghost Hunt", "The Los Village", "Pupa", "Ghost Stories", "Lunar Ledgen Tsukihime", "Junji Ito Collection", "Zetman", "Memories"],
  mystery: ["Earsed", "The Promised Neverland", "Another", "Kakegutui", "Durarara", "Hyouka", "Made in Abyss", "Bungo Stray Dog", "Black Butler", "Monster", "Darker then Black", "Black Bullet", "Tower of God", "When They Cry", "K", "From the New World", "Serial Experiments Lain", "Great Pretender", "Vanpire Knight", "Eden of The East", "No.6", "Summer Time Rendering", "Wolf's Rain", "Amnesia", "High-Rise Invation", "Astra Lost in Space"],
  psychological: ["Deaht Note", "Tokyo Ghoul", "Re:Zero", "Erased", "The Future Diary", "The Promised Neverland", "Psycho-Pass", "Terror in Resonance", "Classroom of the Elite", "Btooom!", "FLCL", "Perfect Blue", "Ergo Proxy", "The Fruit of Grisaia", "Shiki", "Blast of Tempest", "Paranoia Agent", "Cyberpunk: Edgerunners", "Moriarty the Patriot", "Platinum Emd", "B: The Beginning", "Invaded", "When Marnie Was There", "Tomodachi Game", "Haibane Renmei", "Death Billards", "Flowers of Evil"],
  boysLove: ["Given", "No.6", "Love Stage!", "Beyond the Boundary: I'll Be Here - Future", "Junjou Romantica", "Doukyusei -Classmates-", "Hitorijimd My Hero", "Sasaki and Miyano", "Dakaretai Otoko 1-i ni Odosarete Imasu.", "Super Lovers", "Yarchin Bitch-bu", "Gakuen Heaven", "kirepapa", "Yes, No, or Maybe?", "Ten Count", "Fake"]
}


const selectionHandler = e => {
  const genre = e.target.value;
  const targetList = titles[genre];
  if (!targetList) {
    result.innerText = "No anime found";
  } else {
    const randomIndex = Math.floor(Math.random() * targetList.length);
    result.innerText = targetList[randomIndex];
  }
}

const input = document.querySelector('#selectedId');
const result = document.querySelector('#result');
input.addEventListener('change', selectionHandler);
#result {
  padding: 10px;
  background: #eee;
  display: inline-block;
}
<div id="Top">
  <p > Anime for All</p>

  <div >
    <!--MS= format for main section-->
    <h1>Random Anime Generator</h1>
    <label> Select your Favorite genres to generate a anime!</label>
    <select id="selectedId">
      <option>Choose a Genre</option>
      <option value="action"> Action</option>
      <option value="adventure">Adventure</option>
      <option value="comedy">Comedy</option>
      <option value="drama">Drama</option>
      <option value="sliceOfLife">Slice Of Life</option>
      <option value="fantasy">Fantsy</option>
      <option value="horror">Horror</option>
      <option value="mystery">Mystery</option>
      <option value="psychological">Psychological</option>
    </select>
    <p> Your random anime based on chosen genre is....</p>
    <p id="result"></p>
  </div>
</div>

  • Related