vendredi 1 juillet 2022

How do I make a toggle switch trigger a select dropdown to randomize its option value?

I'm setting up a page for a character generator, and I'm giving users the option to either randomize traits or enter their own. I have the "choice vs random" options set up as toggle switches for each trait category, and then if they want to choose their own, I have drop-down select menus for each category with all the traits listed.

Here's my HTML for the switches:

<div class="switch">
            <p>Class</p>
            <label>
              My Choice
              <input type="checkbox" id="class-choice">
              <span class="lever red darken-4"></span>
              Random
            </label>
          </div>

Here's my HTML for the corresponding select menu:

<div class="input-field col s6">
            <select id="classMenu" name="class">
                <option value="barbarian">Barbarian</option>
                <option value="bard">Bard</option>
                <option value="cleric">Cleric</option>
                <option value="druid">Druid</option>
                <option value="fighter">Fighter</option>
                <option value="monk">Monk</option>
                <option value="paladin">Paladin</option>
                <option value="ranger">Ranger</option>
                <option value="rogue">Rogue</option>
                <option value="sorcerer">Sorcerer</option>
                <option value="warlock">Warlock</option>
                <option value="wizard">Wizard</option>
            </select>
            <label for="class">Class</label>
          </div>

What I want to have happen is that every time they click the toggle switch to "random," the corresponding drop-down menu will display a randomized option from the list. I have all the option names saved as an array in my JavaScript:

var charClasses = ["barbarian", "bard", "cleric", "druid", "fighter", "monk", "paladin", "ranger", "rogue", "sorcerer", "warlock", "wizard"];

I know I need to use some sort of $('#class-choice').on("click", ... and a math randomizing function and then something to display that option value, but I guess I'm confused about how to actually do that. I just started learning JS and it's not really intuitive for me yet, so any guidance would be appreciated.




Aucun commentaire:

Enregistrer un commentaire