Can you help me make a JavaScript Random Number Generator that utilizes HTML input fields and buttons?

I am currently working on developing a random number generator that takes user input through HTML. The idea is to have the user enter two values and then click "submit" to receive a random number within that range.

However, I seem to be stuck at this point. What steps should I take next?

Here's an outline of the code so far:

<html>

<input type="text" class="min"><br>
<input type="text" class="max"><br>
<button class="button">Submit</button>

</html>

And here's the JavaScript function for generating the random number:

function myRand(min, max) {

var min = document.getElementByClassName(min).value;

var max = document.getElementByClassName(max).value;

var button = document.getElementByClassName(button);

var result = Math.floor(Math.random()) * (max - min) + min;

return result;
}

Answer №1

Here are a few key corrections to make:

  1. getElementByClassName is incorrect - it should be getElementsByClassName (note the plural "Elements"). This function returns an array of elements, so you will need to access them like
    getElementsByClassName(...)[0].value
    . Alternatively, consider using ids with getElementById.
  2. You are passing arguments min and max to getElementByClassName, which seems incorrect. Perhaps you intended to pass a string, such as getElementsByClassName("min"). This eliminates the need for arguments in the myRand function.
  3. The input field values will be strings, not numbers. To convert them to numbers, use functions like parseInt.
  4. You never actually call the myRand function. To trigger it upon button press, add an onclick listener to the button.
  5. The random number generation logic is flawed. By applying Math.floor to Math.random(), the result always rounds down to 0 since Math.random() generates a value between 0 and 1 (excluding 1). To fix this, adjust the formula to:
    Math.floor(Math.random() * (max - min + 1)) + min

Check out the updated code snippet below, incorporating these fixes. It also demonstrates how to display the result on the screen using getElementById:

https://jsfiddle.net/xv2ne0b9/13/

Answer №2

let minimum = document.getElementByClassName(min)[0].value; let maximum = document.getElementByClassName(max)[0].value;

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

Reverse the order of jQuery toggle animations

Looking for something specific: How can I create a button that triggers a script and then, when the script is done, reverses the action (toggles)? (I am currently learning javascript/jquery, so I am a beginner in this field) Here's an example: ...

The usage of an import statement is not permissible outside of a module

Having some trouble using the mathjs library to calculate complex solutions for the quadratic equation. No matter how I try to import the library into my code, I keep encountering errors. Initially, I attempted this method: At the top of my root.js file, ...

Obtain and utilize the background color to easily implement the same color in another window

For my Chrome Extension project, I am looking to retrieve the background color of the current page and then set the background color of a window to match. Can someone guide me on how to accomplish this using JavaScript (with or without jQuery), and if ne ...

The Alphavantage was acting strangely when I ran a Google script

After following a tutorial video on YouTube, I was confident that my Google script for Google Sheets was working perfectly. However, I encountered two strange issues that I just can't seem to figure out. The code below is exactly what I need - it ...

Cannot locate element using React Testing Library with the selector: [data-testid="task"]

I've encountered an issue while testing a Task component that should be rendered after submitting a form. I'm utilizing redux-toolkit, but despite setting data-testid="task" for the Task component, it doesn't appear in the test DOM ...

The duplication of the Javascript code is creating a conflict within the slider functionality

Attempting to create both an image slider and text slider on the same page using the same JavaScript is proving to be a challenge. Despite researching and trying to implement a no-conflict solution, the sliders still do not function properly together. Wh ...

The jQuery focusout event is triggered on a form element, even if a child element is clicked within the form

How can I ensure that the focusout event is triggered only when the user is not focusing on the entire form element? Currently, if the user clicks on any of the form's inner elements such as the text field or the button, the event is still being trigg ...

Is there a way to use Axios to send several HTTP requests to a URL simultaneously, but pause once a response is received from any one of the requests?

As a beginner in javascript, I am working on writing a script that will use Axios to send multiple HTTP requests to a web server. The server randomly responds to the requests, and I want the script to stop sending requests once it receives a response. This ...

What is the best way to design a Global Navigation menu for websites?

For example, I am looking to integrate a Navigation menu into my website using just one file. I have considered using PHP or creating an HTML frame, but I am wondering what the current industry standard is for professionals. Any insights? ...

Retrieve webpage using HTML stored in web storage

I am exploring a new idea for an application that utilizes local storage, and I am seeking guidance on the most effective way to load content after it has been stored. The basic concept of the app involves pre-fetching content, storing it locally, and the ...

How can a loading bar be shown while a PHP page is loading?

I currently have an HTML form that directs to a PHP file upon submission. The PHP file takes some time to load due to background processes running, so I am interested in implementing a progress bar or alert to indicate when the file is fully loaded. Does ...

I am receiving a success message from webpack indicating that the compilation was successful, but I am encountering a blank page in the

My app.js looks like this: import Home from "./pages/home/Home"; import Login from "./pages/login/Login"; import Profile from "./pages/profile/Profile"; import Register from "./pages/register/Register"; import { Brow ...

Exploring collapsible data tables in Angular with Bootstrap styling

I am attempting to transform my static bootstrap data table, which displays the total count of fruits harvested in various months in an incremental manner, into a dynamic one using the JSON provided below: JSON { "fruit": [ { "fruitName": "Al ...

How to determine if a radio button has been selected using Javascript?

I have come across scripts that address this issue, however they are only effective for a single radio button name. My case involves 5 different sets of radio buttons. I attempted to check if it is selected upon form submit. if(document.getElementById(&ap ...

The React Router Dom V6 triggers loaders as soon as the router is initialized

I'm currently working on implementing routing into my application using react-router-dom V6, specifically utilizing the new createBrowserRouter function and RouterProvider component. The issue I'm facing is that when attempting to integrate a lo ...

Steps to isolate the "changed" values from two JSON objects

Here is a unique question that involves comparing JSON structures and extracting the differences. A JqTree has been created, where when the user changes its tree structure, both the "old" JSON and "new" JSON structures need to be compared. Only the values ...

If you press Ctrl + F, the browser will disable the form search function

How can I prevent the form find browser functionality when pressing Ctrl+F, and instead focus on the element html? <div id='demo'> <form class="id5-text-find-form" id="id5-text-find-form"> <input class="search" placeho ...

Exploring the intricacies of defining Vue component props in TypeScript using Vue.extend()

Here is a simple example to illustrate my question When I directly define my props inside the component, everything works fine <script lang="ts"> import Vue, { PropType } from "vue"; export default Vue.extend({ props: { col ...

Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FA ...

Steps for deactivating the submit button once confirming the presence of the username and email

When using AJAX to verify the existence of an email or username in the database, I want to deactivate the submit button if either one (or both) already exist. Currently, I have successfully changed the input border color but I am facing a challenge with t ...