vendredi 7 mai 2021

Chained selects that update apropriately after Math.random() event

I am migrating an Excel pet project of mine to HTML and javascript. I need child selects to remain constrained to their parent select during a shuffling event. Currently the chained selects work wonderfully under manual selection, but when I shuffle the form the child chained select randomizes its entire pool regardless of what its parent selects.

Script:

var raceSubRace = {
    dwarf: ["Mountain Dwarf", "Hill Dwarf"],
    elf: ["High Elf", "Drow Elf"],
    human: ["Melanistic Human", "Amelanistic Human"]
    };
    $(function(){
    $('#race').change(function() {
        var x= $('#race').val();
        $('#subRace').html("");
        for(index in raceSubRace[x]) {
            $('#subRace').append('<option value="' + raceSubRace[x][index] + '">' + raceSubRace[x][index] + '</option>')
        };
    }).change();
;})

function race() {
    document.getElementById("shuffle").addEventListener("click", function() {
        var select = document.getElementById("race");
        var items = select.getElementsByTagName("option");
        var index = Math.floor(Math.random() * items.length);
        select.selectedIndex = index;
        console.log(select.selectedIndex);
    })
}

function subRace() {
    document.getElementById("shuffle").addEventListener("click", function() {
        var select = document.getElementById("subRace");
        var items = select.getElementsByTagName("option");
        var index = Math.floor(Math.random() * items.length);
        select.selectedIndex = index;
        console.log(select.selectedIndex);
    })
}

HTML:

            <div>
                <label>Race</label>
                <select class="charSheet" id="race" name="race">
                    <option value="dwarf">Dwarf</option>
                    <option value="elf">Elf</option>
                    <option value="human">Human</option>
                </select>
                <label>Sub Race</label>
                <select class="charSheet" id="subRace" name="subRace">
                </select><strong> Note; selection pool will depend on base Race.</strong>
            </div>
        <button id="shuffle" type="button" onclick="shuffle()">Shuffle Form Items</button>

So far all I think of is having a shuffle2 button intended to be pressed after shuffle, but I'm not sure that would even work, and it isn't ideal.




Aucun commentaire:

Enregistrer un commentaire