Generating Words using JavaScript

I have been working on creating a word generator that prompts the user to input ten strings and then outputs a randomly selected one. However, instead of displaying the user input string, it is currently generating a random number. I am not encountering any errors but cannot figure out how to make it work correctly.

Does anyone have any suggestions or ideas on how I can modify this code to display the user input correctly?

I have been stuck on this issue for the past few days and would greatly appreciate your help.

function randomWordGenerator() {

    // Define variables
    var userInput = [];
    var answer = [];
    var range = 1;
    
    // Prompt for Strings
    for(var index = 0; index < 10; index++) {
        userInput[index] = prompt("Please enter string " + (index + 1));
        document.write("You entered: " + userInput[index] + "\n");
    }
    
    // Generate Random Number
    for(var i = 0; i < range; i++) {
        answer[i] = Math.floor((Math.random() * 10) + 1);
    }

    // Display Randomly Selected String
    document.write("The generator chose: " + userInput[answer[0]-1]);
}
randomWordGenerator();

Answer №1

To properly save user input into an array, you need to make sure you are not overwriting the variable every time a new word is entered. Instead of storing only the last word, all inputs should be saved in the array and then you can generate random numbers based on that array. Here's how you can achieve this:

function storeUserInput() {

  // Initialize variables
  var wordsArray = [];

  // Request String Input
  for (var index = 0; index < 10; index++) {
    var userInput = prompt("Please enter a string." + (index + 1));
    wordsArray.push(userInput);
    document.write("You entered: " + userInput + "\n");
  }

  // Choose random word from the array containing all user inputs
  var selectedWord = wordsArray[Math.floor(Math.random() * wordsArray.length)];

  // Display the randomly picked word
  document.write("The generator chose: " + selectedWord);
}

storeUserInput();

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

I recently started delving into React Native and am currently exploring how to implement custom fonts in my application. However, I have encountered an error that is preventing me from successfully integrating

The Issue: The error I encountered only appeared after including font-related code (such as importing from "expo-font" and using "AppLoading" from "expo", and utilizing the "Font.loadAsync()" function). Error: Element type is invalid: expected a string (fo ...

Attempting to resolve an error message with the help of JQuery

I need help figuring out how to clear an error icon when a user presses a key. ** EDIT - including the HTML code ** <input class="validate" type="text" data-type="string" id="address" /> <input class=" ...

Converting function arguments into key/value pairs: A simple guide

I am looking for a way to achieve the following in NodeJS: a = 10 b = 20 c = 30 d = 40 ...... ...... function createObject(a, b, c, d, ....) => { // This function is expected to return an object. // return { a : 10, b : 20 ...

Whenever I attempt to import the "Highway" package, I encounter an error stating "Unexpected identifier."

After installing Highway through the terminal, I encountered an issue when running the script below: import Highway from '@dogstudio/highway'; import Fade from './transition'; const H = new Highway.core({ transition: { default: ...

Send users with session user roles to their designated dashboards

I need assistance with redirecting users based on their user role stored in the session array. I am encountering an issue where the redirection to the admin dashboard is not functioning as expected. Can someone provide some guidance on resolving this mat ...

Is it possible to process HTML and JavaScript as a request in JMeter?

After receiving a response, I noticed that the HTML body contains a hidden form along with an internal JavaScript function to submit the form (view snapshot here). Is there a method in JMeter to execute JavaScript code that directly submits a form? I am ...

What is the best way to send an HTTP request in AngularJS to receive data in JSON format?

I am trying to create an AngularJS app that can send HTTP requests for JSON data. I have written the code in my index.html file to request JSON data using AngularJS, but for some reason, the JSON data is not being printed. When I check the console in Fire ...

Transferring arrays through Ajax with PHP

Currently, I am attempting to pass an array in my Ajax request to update multiple elements with one query. This is the approach I am taking: My Ajax function looks like this: $("body").on("focusout", "input", function () { var id = ($(this).attr("id" ...

Managing the state of dynamically changing forms in React

I am dealing with a dynamic form that expands in an unpredictable manner based on user input. I'm able to capture all the user inputs from the form as React State. When the form is submitted, I convert the State (JSON) into a YAML file. The JSON stru ...

Tips for incorporating css styles and javascript into handlebar files

I've been trying to figure out how to add styles and js to my handlebar files, but I'm hitting a roadblock. I attempted to use partials to store the stylesheet tags and then include those partials in the handlebars file, but it didn't work a ...

The data type 'string' cannot be assigned to type [object]

Here's a scenario using an interface: interface Order { symbol: string side: string price: number quantity: number } In my code, I have a section where I am trying to access values within a table. However, it's giving me an error saying tha ...

What is the process for adding content to a textarea field?

Is there a way to dynamically update a textarea using PHP and trigger the refresh of the textarea? APPRECIATE IT Edit: The solution should be initiated by server-side PHP code ...

What is the best way to sum up array elements until they equal a target number, and then create objects using these summed values?

Suppose I have an array containing 5 different values for width, with a maximum width of 6 that needs to be reached. How can I iterate through the array and construct an object with those values each time it hits the maximum value without exceeding it? Le ...

Check the email for accuracy and show as needed

I need help verifying email validity in JavaScript and displaying an alert box if it's invalid. If the email is valid, I want to display div2 instead. However, my current code doesn't seem to be working as expected. Below is the JavaScript code ...

Error trying to import: 'Navbar' is not available from '@/components/Navbar' (imported as 'Navbar')

Having trouble adding a navbar and footer to my nextjs project without using layout. Here is how my files are structured. https://i.sstatic.net/D7Fx3.png Check out the code below: import './globals.css' import { Inter } from 'next/font/goo ...

Ways to stop VoiceOver from selecting the background content when a modal is open

Is there a way to prevent VoiceOver from reading the content behind a modal? I tried using aria-modal=true, but it seems VoiceOver does not support this feature by default like NVDA and JAWS do. I found more information about this on . According to the in ...

How can I rename attribute values in a dropdown menu and ensure they work properly?

I'm facing an issue with my code. How can I store the option values in a database when they have numbering like value="1" or value="2"? Can I change it to something like value="1000" and have the other select box change to value="250" when selected? ...

Typescript version 2 is facing difficulties in resolving an external node module

Lately, I've been experimenting with prototyping using koa and Typescript 2.0. In my simple project, I've configured the tsconfig.json file like this: { "compilerOptions": { "outDir": "./bin/", "sourceMap": true, "no ...

Uploading Images Dynamically with Ajax and jQuery in PHP

[Resolved Previous Issue] Recently, I obtained an image upload script that utilizes Ajax and jQuery. My goal is to restrict the maximum number of uploads to just 8 images. Any suggestions or advice would be greatly appreciated. Source of Download: ...

Modifying a variable within an arrow function does not result in the variable being changed when checked outside of the arrow

I am currently developing an application with Angular and Typescript where I need to update the value of a variable inside a function. To retrieve the data required, I'm utilizing a service. Below is the code snippet for reference: let isDataAvailab ...