mardi 2 mars 2021

Randomly selecting a pushed value with an input from an array with a button in JS

i have the following code:

    <input type="text" id="wisselspelers" onkeypress="return (event.charCode == 32|| event.charCode > 64 && 
    event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)">
    <button id="opslaanBtn">Wisselspeler toevoegen</button>
    <p id="opgeslagen"></p>

    <script>
        document.getElementById("opslaanBtn").addEventListener("click", myFunction)
        document.getElementById("opslaanBtn").addEventListener("click", myFunction2)

        var spelers, ab1, abc2, abcd3;
        var spelers = [];

        function myFunction() {
            var input = document.getElementById("wisselspelers").value;
   
            spelers.push(input);

            abc2 = spelers.length;
            ab1 = "<ul>";
            for (abcd3 = 0; abcd3 < abc2; abcd3++) {
                ab1 += "<li>" + spelers[abcd3] + "</li>";
            }
            ab1 += "</ul>";
            document.getElementById("opgeslagen").innerHTML = ab1;
        }

        function myFunction2() {
            document.getElementById("wisselspelers").value = "";
        }

    </script>

This code allows someone to enter a value into the input and add it to the array. I'd like to create another button, which allows a user to randomly select one of the values he added to the (empty) array.

I've tried the following code, but this code shows everything the user added and doesn't randomly select one:

  <button id="gekozenBtn">Kies een random wisselspeler</button>
    <h1 id="gekozen"></h1>

    <script>
        document.getElementById("gekozenBtn").addEventListener("click", gekozenFunction)

        var rand = Math.floor(Math.random() * spelers.length);
        var concat = spelers[rand];
        
        function gekozenFunction() {
            document.getElementById("gekozen").innerHTML = (concat);
        }
    </script>



Aucun commentaire:

Enregistrer un commentaire