How can I generate two matching elements simultaneously from an array using the random function in Javascript?

How can I ensure that when using the random feature, two items from my array list that belong together are generated at the same time? Specifically, when clicking on the "get Name and Grade" button, I want to display a random name in one box and its corresponding grade in another. Currently, I am only able to get random names and grades that do not match up. How can I correct this issue?

<!DOCTYPE html>
<html> 

<head> 
<meta charset="UTF-8">
<title>javascript</title>

<script type="text/javascript">


    var names = [];
    var grades = [];

    names[0]="Klara";
    grades[0]="A";
    names[1]="Sarah";
    grades[1]="A";
    names[2]="Andrea";
    grades[2]="B";
    names[3]="Emil";
    grades[3]="C";
    names[4]="Victor";
    grades[4]="C";
    names[5]="Alicia";
    grades[5]="D";
    names[6]="Thomas";
    grades[6]="E";
    names[7]="Robert";
    grades[7]="E";



    function getName()
    {
        var rand = names[Math.floor(Math.random() * 8)];
        return rand;
        var box =document.getElementById('getName');getName.value=getName;

        }

   function box(){
   var box =document.getElementById('getName');getName.value=getName;
   }



            function getGrade()
    {
        var rand = grades[Math.floor(Math.random() * 8)];
        return rand;
        var box =document.getElementById('getGrade');getGrade.value=getGrade;

        }

   function box2(){
   var box2 =document.getElementById('getGrade');getGrade.value=getGrade;
   }






</script>


</head>
<body>

<form>

    <input type="text" name="box" id="box" value=""/> <br/>
    <input type="text" name="box2" id="box2" value=""/> <br/>
    <input type="button" name="textbox1" id="textbox1" value="Get Random Name and Grade" onclick="document.getElementById('box').value = getName(),document.getElementById('box2').value = getGrade()"/> 
    </form>    






</body>
</html>

Answer №1

Your example contains several syntax errors and odd function calls, but let's overlook those for now.

An improved approach would be to store the data in objects, keeping related information together:

var students = [
    {Name: "Klara", Grade: "A"},
    {Name: "Sarah", Grade: "A"}
];

You can then access the values like this:

students[0].Name;
students[0].Grade;

Edit:

<html> 
    <head> 
        <script>
            var studentsData = [
                     {Name: "Klara", Grade: "A"},
                     {Name: "Sarah", Grade: "A"},
                     {Name: "Andrea", Grade: "B"},
                     {Name: "Emil", Grade: "C"},
                     {Name: "Victor", Grade: "C"},
                     {Name: "Alicia", Grade: "D"},
                     {Name: "Thomas", Grade: "E"},
                     {Name: "Robert", Grade: "E"}
            ];

            function getStudent(){
                return studentsData[Math.floor(Math.random() * studentsData.length)]
            }

            function setValues(){
                var inputBox1 = document.querySelector('#box');
                var inputBox2 = document.querySelector('#box2');
                var student = getStudent();

                inputBox1 && (inputBox1.value = student.Name);
                inputBox2 && (inputBox2.value = student.Grade)
            }
        </script>
    </head>

    <body>
        <form>
            <input type="text" name="box" id="box" value=""/> <br/>
            <input type="text" name="box2" id="box2" value=""/> <br/>
            <input type="button" name="textbox1" id="textbox1" value="Get Name and Grade" onclick="setValues()"/> 
        </form>
    </body>
</html>

Answer №2

After some updates, my code now appears like this. However, upon pressing the button to fetch grade and name, I am receiving [object Object] in each textbox and unable to find a solution.

<!DOCTYPE html>
<html> 

<head> 
<meta charset="UTF-8">
<title>javascript</title>

<script type="text/javascript">


    var  tName = [
         {Name: "Klara", Grade: "A"},
         {Name: "Sarah", Grade: "A"},
         {Name: "Andrea", Grade: "B"},
         {Name: "Emil", Grade: "C"},
         {Name: "Victor", Grade: "C"},
         {Name: "Alicia", Grade: "D"},
         {Name: "Thomas", Grade: "E"},
         {Name: "Robert", Grade: "E"}
    ];

    tName[0].Name;
    tName[0].Grade;
    tName[1].Name;
    tName[1].Grade;
    tName[2].Name;
    tName[2].Grade;
    tName[3].Name;
    tName[3].Grade;
    tName[4].Name;
    tName[4].Grade;
    tName[5].Name;
    tName[5].Grade;
    tName[6].Name;
    tName[6].Grade;
    tName[7].Name;
    tName[7].Grade;


    function getName()
    {
        var rand = tName[Math.floor(Math.random() * tName.length)];
        return rand;
        var box =document.getElementById('getName');getName.value=getName;

        }

   function box(){
   var box =document.getElementById('getName');getName.value=getName;
   }



   function box2(){
   var box2 =document.getElementById('getName');getName.value=getName;
   }






</script>


</head>
<body>

<form>

    <input type="text" name="box" id="box" value=""/> <br/>
    <input type="text" name="box2" id="box2" value=""/> <br/>
    <input type="button" name="textbox1" id="textbox1" value="get Name and Grade" onclick="document.getElementById('box').value = getName(),document.getElementById('box2').value = getName()"/> 
    </form>    






</body>
</html>

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

Turn off Closure Compiler formatting guidelines

I've inherited an old codebase that's been minified using Closure Compiler. As part of our efforts to modernize and optimize the code, we've set up a CI job to highlight any warnings or errors. However, some of these warnings are irrelevant ...

Unexpected issues arose with the seemingly straightforward Angular/Node application

Recently, I developed a basic application using Angular and Node which serves as a chat platform. One interesting feature is that it utilizes ng-model on a text field. However, I encountered an issue where the message being emitted by the node was consist ...

Having trouble with setting up local notifications in React Native's scheduling feature?

I have integrated the react-native-push-notifications npm library into my application to enable notifications. However, I am facing an issue while trying to schedule notifications using PushNotification.localNotificationSchedule. The code snippet for this ...

Guidelines for securing login access where the "IsApproved" field must be true before authorization

During the account registration process, I initially set the default value to false for the field IsApproved. I need to create security rules that allow login only for users with IsApproved:true, and redirect those with IsApproved:false to the accessdenied ...

What is the best way to transfer data from one function to another file in React without directly calling the component or using props?

filename - Header.jsx import { useEffect, useState } from 'react' import { getValue } from './Input' import TextField from '@mui/material/TextField'; export const Header = () => { const [search, setSearch] = useState( ...

Issue with implementing Alert component in React Hooks with Bootstrap

Currently, I am working on a project that allows users to nominate their favorite movies. As part of this project, I am trying to implement an alert message that will appear when the submit button is clicked to finalize all the nominations. {"return (" ...

The usage of block-scoped declarations like let, const, function, and class is not currently enabled outside of strict mode in the Krias

Just diving into the world of React and ES6, I decided to start with the boilerplate "https://github.com/kriasoft/react-static-boilerplate". Following the instructions in the documentation, I went ahead with npm install -> node run. However, I encounte ...

Progressive Web App (PWA) default start URL

I am currently facing an issue with my Vue app, which is also a Progressive Web App (PWA). While the PWA functions correctly as planned, I realized that I am using generic paths for my web application. This means that in order to access the correct page, ...

Verify the definition of the checkbox

I'm attempting to determine whether a checkbox is defined and unchecked. When the page loads, my checkbox is disabled and I receive an error indicating that it is undefined. I attempted to create a condition to prevent the error but was unsuccessful. ...

When integrating react-router 5 and redux 7, there is an issue where the state is not being reset when navigating to a new route using react-router's <Link

My current setup includes the following versions: `"react-router": "^5.2.0",` `"react-router-domreact-router": "^5.2.0",` I'm unsure if my setup is compatible with React-router 5 as I was using a version prior ...

Exploring the functionality of componentWillReceiveProps within functional components

Embarking on my journey with functional components after extensively working with class components. While experimenting, I encountered a challenge: how can I incorporate the functionality of componentWillReceiveProps within the context of the useEffect h ...

Searching for distinct elements between two arrays of different lengths can be accomplished by iterating through both

Similar Question: array_unique with two arrays Looking for a way to identify unique elements between two differently sized arrays?? $array1 = array(2,1,1,3,5,5); $array2 = array(2,1,3,5); ...

Transfer a text input value from PHP to JavaScript

Within my WordPress backoffice, I set up a field to select a label for a highchart like this: public static function sm_register_chart() { $charts = array(); if( function_exists( 'wdt_get_all_charts_nonpaged')){ foreach( wdt_get ...

The query limit issue in Sails JS

I am encountering a 413 (Request Entity too large) error when making a request to a Sails Js app (v0.12). Despite my attempts to raise the request limit in the bodyParser, I have not seen any changes take effect. In config/http.js, I included a customize ...

Converting the structure of an object into an array structure for highcharts can be achieved through

I am looking to transform the object structure below: [ { "tahun": "2010", "apel": 100, "pisang": 200, "anggur": 300, "nanas": 400, "melon": 500 }, { ...

Optimizing your webpack configuration to fully bundle the assets folder

Currently, I am in the process of developing a Web Application utilizing the MEAN stack. For bundling my files, I have implemented webpack. Within my project, there are two main folders: 1.public/assets (which contains subfolders like CSS, js, etc. housi ...

What is preventing the code from concealing the html div when the winOrNot function is given the argument (false)?

Can you identify why the "Congratulations" message in the div is not being hidden when the function is called with the (false) argument? <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div id= ...

Is it impossible to modify the value of a cookie that has been established in JavaScript

I have an <asp:CheckBox OnClick=""> linked to a JavaScript function that sets a cookie value like this: document.cookie = "cv0_value=1"; In my .Net code-behind, I am retrieving the cookie value using the following code, and everything seems to be f ...

Display information from a string array using androidplot

I have been working on plotting data received via bluetooth communication with a microcontroller board on my android device. The data is transmitted every 200 ms in the form of a string of 4 characters (4 digits), which I display using a textView in the Ma ...

Commands behaving strangely when used with Powershell arrays

As a former Linux user, I am venturing into the world of automating Veeam Backup job retrieval through PowerShell scripting. I decided to experiment with PowerShell arrays by testing it out with a simple example: $users = 'mark','josh&apos ...