JavaScript Array Randomizer with the Ability to Add Names to the List

I've been working on a JavaScript program lately. It's supposed to randomly select two characters from Once Upon A Time and match them up. The randomizing part is fine, but I'm struggling with the "Add Name to Array" feature. Here's my code snippet:

<center>
<b>
<input type="button" value="Randomize!" onclick="ouatRandomizer();">
<b>
<p id="text"></p>
<input id="name" type="text" placeholder="Add a Name" />
<input type="button" value="Add Array" onclick="addToArray();">
</center>

<script>

var nameInput   = document.getElementById("name");

var names = ["Hook", "Rumpelstiltskin", "Belle", "Emma", "Regina", "Aurora", "Elsa", "Anna", "Snow White", "Prince Charming", "Cora", "Zelena", "August", "Mulan", "Graham", "Discord", "Will", "Robin Hood", "Jiminy Cricket", "Henry", "Neal", "Red"];
var nameone = names[Math.floor(Math.random() * names.length)];
var nametwo = names[Math.floor(Math.random() * names.length)];
message = "Your characters are.. " + nameone + " and " + nametwo + ".";


function ouatRandomizer() {
    nameone = names[Math.floor(Math.random() * names.length)];
    nametwo = names[Math.floor(Math.random() * names.length)];
    message = "Your characters are.. " + nameone + " and " + nametwo + ".";
    document.getElementById("text").innerHTML = message;
}

function addToArray( name ) {
    names.push( name );
    console.log(names.join());
}



</script>

I want the program to accept any name in the input box and automatically incorporate it into the randomization process. It doesn't need to store the name permanently. If that's possible, great!

Thank you for taking the time to address my issue and provide help. Just a couple of things to note: I'm new to these forums and not very familiar with them yet, so please bear with me. Also, if you can explain the code briefly but clearly, as I'm still learning and navigating this environment.

Thanks again!

Answer №1

First and foremost, it's important to note that while Math.random() serves as a pseudo-random number generator, your current randomization algorithm shows bias towards the beginning of the array, never reaching beyond "Graham".

To rectify this issue, consider utilizing the following randomizer instead:

/*
 * 
 * @param upper_bound represents the total count of elements within your array.
 * 
 */
function randomize (upper_bound) {
    return Math.floor(Math.random() * upper_bound);
}

In response to your query, be sure to capture the input value prior to invoking the addToArray() function.

Replace

<input type="button" value="Add Array" onclick="addToArray();">

with

<button onclick="addInput()"></button>

Add the following function to your script:

function addInput () {
    var name = document.getElementById("name").value;
    addToArray(name);
}

I trust this guidance proves beneficial.

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

Filter Angular.js by precise values (exact match)

Check out this HTML code snippet: <ul ng-repeat="friend in friends | filter: { age: '2' } | orderBy: 'name' "> <li>{{friend.name}}</li> </ul> Here is the $scope variable being used: $scope.friends = [ ...

What is the most efficient way to perform an inline property check and return a boolean value

Can someone help me with optimizing my TypeScript code for a function I have? function test(obj?: { someProperty: string}) { return obj && obj.someProperty; } Although WebStorm indicates that the return value should be a boolean, the TypeScript compil ...

Creating a subclass in JavaScript ES6+ that directly returns an object within its constructor

I am facing an issue with extending a Javascript ES6+ class that returns an object from the constructor. Consider the following scenario: class Base { constructor() { return {name: "base"} } } class Extension extends Base { constructo ...

Tips for creating a vertical wave animation of a ribbon using svg

I have an SVG code for a vertical ribbon that I want to add a wave effect to. The wave should start from the top and flow continuously to the bottom, but currently it's not working as expected. @keyframes thread{ from { stroke-dashoffse ...

The issue lies in the error code TS2315 which states that the type 'observable' is not a generic

I keep encountering an error message that says 'observable is not generic' while importing files. I am working on implementing CRUD operations in Angular 7, where I have created two components for adding and listing employees. The functions for c ...

Tips for dynamically loading images as needed

I'm working on a simple image zoom jQuery feature using elevateZoom. You can see a Demo example here. The implementation involves the following code: <img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/> <sc ...

The error message "TypeError: jQuery(...).ready(...) is not a function" indicates that

Although this question has been asked before, none of the answers seem to solve my specific issue. I am attempting to run a small piece of jQuery code (as I am just starting to learn it). jQuery(document).ready(function(){ jQuery('.comtrig') ...

Accessing elements from a multidimensional array in PHP using a foreach loop

My current code is supposed to retrieve the array for each key inside a loop, but the resulting array is incorrect. Instead of individual arrays, the DataIds returned is a combination of all arrays. I need assistance in PHP to modify my code so that I ca ...

Anticipating the moment when images finally appear after switching out the div

Currently, I am working on an AJAX call that replaces a particular div in my project: $.post(url, function(data) { $('#product_list').first().replaceWith(data.products); }); A little issue I am encountering is with the images that have a w ...

What is the best way to create a sliding <nav> effect when a <div> is clicked?

Hello! I am looking for a solution that will cause the navigation contents to slide out from the left when the div class "bt-menu" is clicked. It should also slide back in to the left either when the div is clicked again or when anywhere outside of the nav ...

Filtering a string array in Angular based on an object's value

I am facing a challenge with two arrays in my code. The first array, $scope.termini, contains strings, and the other one, $scope.reserved, contains objects. Each object in the second array has a variable called vrijemeTermina. My goal is to filter $scope.t ...

The function is not recognized in C# programming language

Whenever I try to trigger functions by clicking buttons, nothing seems to happen and an error message appears in the console. Uncaught ReferenceError: AddressInputSet is not defined at HTMLButtonElement.onclick I'm new to this and could use ...

Mastering keyframe animation with Three.js

Hello everyone, I am new to posting and I have a question that I haven't been able to find the answer to anywhere else. Just to clarify, I am not a professional programmer, more of a 3D graphic designer ;) I am interested in importing json models wit ...

Achieve a seamless redirection to the 404 component in Angular without altering the browser URL, while ensuring that the browsing

Whenever my backend sends a 404 error (indicating that the URL is valid, but the requested resource is not found, such as http://localhost:4200/post/title-not-exist), I need Angular to automatically redirect to my NotFoundComponent without altering the URL ...

Is there a simpler method to access the source element for an event?

I'm just starting to learn JavaScript and jQuery, and right now I have the following code in my HTML: <a id="tog_table0" href="javascript:toggle_table('#tog_table0', '#hideable_table0');">show</a> After that, I hav ...

Loading screen featuring an outlined blueprint of design elements

Can anyone identify the technology or language used to create the preloader screen on websites like the one shown in this link? The elements have a sweeping shine effect while loading. This style of preloader screen can be seen on popular websites such as ...

Adding attributes dynamically to input elements in a React render function

I currently have an input tag inside my render function which looks like this: <input id="time" type="time"> I am now looking to dynamically add the value attribute to it. Is there a way to achieve this in React? Thank you for your help in advance ...

The secret equation for unravelling an array of gridded numbers, including

I have been using this method to flatten a multidimensional array (x,y,z): array = new byte[GridSizeX*GridSizeY*GridSizeZ]; index = x + y * GridSizeX+ z * GridSizeX* GridSizeY; I am now trying to figure out how to adjust this formula to handle n ...

Finding the correlation between SVG element IDs and JSON keysUnderstanding how to pair up

Currently, I have an SVG file that can be viewed here. My goal is to present specific data when elements within the SVG are clicked. The data is in JSON format and I am looking to match each ID of an SVG element with a key in the JSON data. If both the key ...

Java Array Index Out of Bounds Exception: A Common Pitfall

package test1; import java.util.Scanner; public class Question2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int traincars; int maxweight; int count = 0; int total = 0; ...