Populate an array with user input values and shuffle the content for random display

I am currently encountering a challenge. I am aiming to design a form that gathers 4 nicknames after submitting the form, and then exhibits them randomly in HTML code using JavaScript

My 4 input values are stored in an array. I need to display them randomly into two separate teams.

I am attempting to generate a random index, ensuring it differs from those already allocated to prevent one individual being on both teams. The code seems to function well; however, occasionally, one player is assigned to both teams. Following this occurrence, the randomizer malfunctions... Any suggestions?

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
}

Your assistance would be greatly appreciated!

Answer №1

Are you looking for a simple method to select a random item from your array?

First, populate your array with items like this:

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

Next, here's how you can retrieve a random element:

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

Note that Math.random() never reaches exactly 1, so the maximum index will always be one less than the length of the array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bizarre error in rendering angular template

Included in my index.html file is the following code: ...... <my-test-app></my-test-app> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/angular-component-router/angular_1_router.js"> ...

Increasing the number of elements in a multi-dimensional array in React

Hello everyone, I am reaching out because I am having trouble with my work schedule. I need to update each checkbox based on whether it is true or false (tasks array contains checkboxes in the front end). Data seeds const datas = [ { id: 10, ...

Learn the process of filtering an array using another array

I have a collection of items set up in the following format. items = [ { id: 1, status : "Active" // Other fields tags : [{val: 'IGM', color: 'light-success' }, {val: 'Gated Out', colo ...

The Photoswipe default user interface cannot be located

While attempting to incorporate PhotoSwipe into my website, I encountered an uncaught reference error related to The PhotoswipeUI_Default is not defined at the openPhotoSwipe function Below is the code snippet that I have been working on: <!doctyp ...

Executing an http.get request in Angular2 without using RxJS

Is there a method to retrieve data in Angular 2 without using Observable and Response dependencies within the service? I believe it's unnecessary for just one straightforward request. ...

Please refrain from including HTML code within the div element

When I input the following text inside a textarea: <strong>test</strong> and then display it within a div, the text appears in bold instead of showing the HTML code as entered. How can I prevent the HTML code from being rendered and instead d ...

What is the best way to update a form without refreshing the DOM?

Is it possible to update a form with user-modified data without reloading the DOM when someone clicks the submit button? My app currently works perfectly but only updates the form when the DOM is reloaded. Server Code: "use strict"; // Server code here ...

Tips for utilizing the Apollo cache consistently during page transitions in NextJs

In the official examples repository of NextJS, I found this apolloClient.js file: import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client' import { concatPagination } from '@apollo/client/utilities' import merge from &apos ...

Smoothly animate a Three.js object in response to an event without changing its current position

I need assistance with slowing down the rotation animation of a cube when a mouse hovers over it and making it continue smoothly on mouse leave. The current issue I'm facing is that when the mouse enters the cube, the rotation slows down but abruptly ...

Glass-pane or angular/HTML overlay on a designated element

Is there a way to create a glass-pane effect, like an hourglass symbol on a semi-transparent layer, within the boundaries of an HTML element E? The goal is to have the glass-pane only overlap the area within E's boundaries. When the glass-pane is ac ...

Concealing aspects of my game until a specific criteria is fulfilled

After successfully disabling and enabling tabs, my goal now is to hide elements until a player unlocks something, making it more rewarding. I attempted to achieve this by using the following code: <div id="turtle" style="visibility: hidden;"> ...

The custom service is failing to load, in the simplest terms possible

After creating a dataService.j that contains the following: angular.module('dataService', []) .service('gameDataService', function() { var _gameData = { loggedIn: "false", gameJoined:"false", tableFu ...

Dynamic horizontal scrolling

I need help implementing a site using React that scrolls horizontally. I'm unsure how to implement certain aspects, so I am looking for some assistance. Within a wrapper, I have multiple container Divs. <div class="wrapper"> <div class=" ...

Error in JSON due to the presence of an unexpected token within the

I am facing a challenge with my PHP code, where I take a list of filenames or empty strings and store them in an array. This array is then converted to JSON and saved in a database successfully. However, the problem arises when this array is also stored wi ...

Running javascript code with variable in selenium

I am attempting to run a JavaScript statement that includes a variable. How can I correctly pass the variable to the statement? Language: Python val = "changed" javaScript = f'document.querySelector("h2").textContent = "{val}"' driver.execute_sc ...

solving the enigma of this Javascript script

Currently, I am attempting to find a way to have the featured area on link to other webpages instead of showing them within the featured box on the left. This section is utilizing a JS file to present videos and content in the featured box when various ...

JavaScript regular expressions only recognize certain characters

When submitting a form, I need to validate a field and ensure that only specific characters are allowed. The permitted characters include: a-z A-Z 0-9 % . " ' & - @ # $ * / + = [ ] ! I attempted to use the following regex for validation: var r ...

Unable to place a div within a nested div

Can you assist me in resolving an issue I am facing? I have the following code: <div id="div1"> <div id="edit1"> hello <input type="button" id="b1" onclick="aaa()"/> </div> </div> I am trying to insert ...

Load HTML/erb templates efficiently in Rails to optimize performance for AngularJS applications

I recently came across a discussion about eager loading HAML templates on this website. The concept of caching HTML partials to enhance performance in Angular applications caught my attention. However, I'm curious to know if there is a similar approac ...

"An error occurs when attempting to clear Rad Grid data with javascript: htmlfile: Invalid argument thrown

Hello, I am currently developing an ASP.NET application. I am facing an issue where I need to clear the data in a Rad grid upon button click using JavaScript. The code snippet that I have attempted for this is as follows: document.getElementById(&a ...