set input values in array and randomize content to display

146 Views Asked by At

I can't seem to find any solutions. I want to create a form that collects 4 nicknames after submit a form and then displays them all randomly in html code using javascript

My 4 input values are now in an array. I have to display them randomly in two different teams.

I'm trying to get a random index, and as long as it's different from the ones already assigned to avoid one person being on both teams. This code works, but sometimes, one player is assigned to 2 teams. Then, the randomizer doesn't work... Do you have an idea ?

function getRandomNumber(max) {
    return Math.floor(Math.random() * Math.floor(max));
  }

function getData() {

    let joueur1     = document.querySelector("#player1").value;
    let joueur2     = document.querySelector("#player2").value;
    let joueur3     = document.querySelector("#player3").value;
    let joueur4     = document.querySelector("#player4").value;

    playerList.push(player1.value);
    playerList.push(player2.value);
    playerList.push(player3.value);
    playerList.push(player4.value);

        randomNumber1           = getRandomNumber(playerList.length);
        last1 += randomNumber1;
        random1.textContent     = playerList[randomNumber1];
        do {
          randomNumber2         = getRandomNumber(playerList.length);
        } while (randomNumber2  == last1 && last4 && last3);
        last2 += randomNumber2        
        random2.textContent     = playerList[randomNumber2];

        do {
          randomNumber3         = getRandomNumber(playerList.length);
        } while (randomNumber3  == last1 && last2 && last4);
        last3 += randomNumber3
        random3.textContent   = playerList[randomNumber3];

        do {
          randomNumber4         = getRandomNumber(playerList.length);
        }while (randomNumber4   == last1 && last2 && last3)
        random4.textContent     = playerList[randomNumber4];
        last4 += randomNumber4
}

Thanks for your help !

1

There are 1 best solutions below

3
On

Here is a simple way of getting a random item from your array

Here you add your items into array

let joueur1     = document.querySelector("#player1").value;
let joueur2     = document.querySelector("#player2").value;
let joueur3     = document.querySelector("#player3").value;
let joueur4     = document.querySelector("#player4").value;
let playerList=[];
playerList.push(joueur1);
playerList.push(joueur2);
playerList.push(joueur3);
playerList.push(joueur4);

Then, Here is how you can get randomized content

let randomPlayer = playerList[Math.floor(Math.random() * playerList.length)];

Math.random() will never be 1. The largest index is always one less than the length of the array