Alert-Enabled Random Number Generation Tool

I'm struggling to create a program that randomly generates a number between 1 and 20. If the number is less than 10, it should display "fail," and if it's greater than 10, it should display "success." I can't seem to figure out where I went wrong. Can someone please help me?

<!DOCTYPE html>
<html>
<body>

<p>Press the button to see a random number between 1 and 20.</p>

<button onclick="myFunction()">Generate Number</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = Math.floor((Math.random() * 20) + 1);
    document.getElementById("demo").innerHTML = x;

    if (x < 10) 
{
    text = (x + “Success”);
}
    else 
{
    text = (x + “Fail”);
}
document.getElementById("demo").innerHTML = text;
}    
</script>

</body>
</html>

Answer №1

It seems like you have made a mistake with the quotes and there are some scope issues in your code. Take a look at this CodePen snippet to identify and correct your errors.

var x=''; 
var myFunction= function () { 
    x = Math.floor((Math.random() * 20) + 1); 
    document.getElementById("demo").innerHTML = x; 

    if (x < 10) { 
        text = x + "Success"; 
    } else { 
        text = (x + "Fail"); 
    } 
    document.getElementById("demo").innerHTML = text; 
} 

Answer №2

Greetings! I noticed a few errors in your code.

All the code should be written within your function called myFunction(); this way, the scope of x will be limited to that function only.

You can easily implement this using jQuery. Take a look at the code snippet and JS Fiddle demo below:

 $(document).ready(function(){  
        $('#btnRoll').on('click',function(){
             var x = Math.floor((Math.random() * 20) + 1);
           var x = Math.floor((Math.random() * 20) + 1);       
           if(x<10)
             $('#demo').html(x+' fail');
           else
             $('#demo').html(x+' Success');
        });
    });

Check out the JsFiddle here

Thank you!

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

Merge web address when form is sent

I'm currently working on a search application using the Django framework and the Yelp API as my backend, which is functioning properly. However, I am facing some challenges with the frontend development, specifically integrating Leaflet.js. My search ...

transforming a div container into an inline element using CSS

Hey there! I'm facing an issue with CSS where I am trying to change a div tag into inline. <div id="menu1"> <ul> <a href="#"> <li> one</li> </a> <a href="#"> <li> two</li> </a> <a h ...

The callback functions, such as afterMove, are not being executed

This code snippet is copied from Owl Carousel's official website. I am having trouble getting the callback functions like afterMove to work. Can anyone help me figure out why the afterMove function is not being called? It seems that none of the callba ...

The script tags encountered an issue loading the resource with a status code of 404

Currently working on an ASP.NET MVC project and encountered an issue on one of the pages. Here is the code snippet with a script included at the bottom... @model IEnumerable<PixelBox.Dtos.ItemGetDto> @{ ViewBag.Title = "Index"; } <body> ...

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...

Using AJAX to send a POST request with the PHP $_FILES superglobal while preventing the default form submission with the onclick

Seeking to implement a photo upload form using an AJAX script that is currently in place. Currently, I have the html form with a file input field. Upon submission, there is an onclick event triggering "PostForm(); return false;" This action directs to a ...

Checking whether a node stream operates in objectMode

When working with a node js stream object, how can I ascertain if it is an object stream in objectMode? For example, suppose I have a readable stream instance: const myReadableStream = new ReadableStreamImplementation({ options: { objectMode : true } ...

Should Redux Reducer deep compare values or should it be done in the Component's ShouldComponentUpdate function?

Within my React Redux application, I have implemented a setInterval() function that continuously calls an action creator this.props.getLatestNews(), which in turn queries a REST API endpoint. Upon receiving the API response (an array of objects), the actio ...

Text in d3.js vanishing while undergoing rotation

I have been struggling for hours with what seems like a simple problem and haven't made any progress. I'm hoping to receive some valuable advice from the brilliant minds on stackoverflow. You can view my demo at I attempted to use jsfiddle to s ...

How to position the navigation bar to the right using bootstrap

I have been experimenting with moving the navigation bar to the right side of the screen in bootstrap4 by using float: right; on the nav a element, but it doesn't seem to be having any effect. I am developing my project using a codepen app. Here is t ...

The benefits of using Node.js for asynchronous calls

Each time a new data is added or existing data is updated, the variables new_data and updated_data will increment accordingly. However, when attempting to output the total count of new_data and updated_data at the end of the code, it always shows as 0. H ...

Adaptable placement of background across screen widths

I am facing an issue with three buttons that have the same height and width, text, and background icons on the right. On small screens or when there is only a single word in the button, I want to move the icons to the bottom center of the button. Is there ...

Toggle the state of a Material UI checkbox in ReactJS based on the data from hooks that return a true or checked value

I need assistance with checking/unchecking a checkbox value in an edit modal based on the return of addAdvisory(hooks) which is 'Y', indicating true/checked. Below is my basic code snippet: const [addAdvisory, setaddAdvisory] = useState({ SY ...

Resolving the Enigma: Querying jQuery for Real-Time Validation and

I'm fairly new to jQuery and I'm facing a challenge in my registration form script. Specifically, I want to check if the entered username or email is already taken while the user is typing. Currently, this functionality works by making a json req ...

Mastering the art of tab scrolling in VueJS using Bootstrap-vue

Currently, I am working on a VueJS project that utilizes bootstrap-vue. The issue I am facing is that when rendering a list of tabs, it exceeds the width of its parent container. To address this problem, I aim to implement a solution involving a set of but ...

An error message 'module.js:557 throw err' appeared while executing npm command in the terminal

Every time I try to run npm in the terminal, I encounter this error message and it prevents me from using any npm commands. This issue is also affecting my ability to install programs that rely on nodejs. $ npm module.js:557 throw err; ^ Error: Cannot ...

Arrow functions do not function properly with Typescript decorators

I've created a typescript decorator factory that logs the total time taken to execute a function, along with the actual function execution results and parameters passed to the decorator. For example: export function performanceLog(...args: any[]) { ...

Ensuring Navigation Elements Remain Aligned in a Single Line

I'm in the process of developing an interactive project that will be showcased on a touch screen. One of its key features is a fixed footer navigation. Currently, I am using floats to position the main navigation elements and within each element, ther ...

Refine JSON data by selecting only distinct key/value pairs

My JSON object has the following structure: var theSchools = { Bradley University: "bru", Knox College: "knox", Southern Illinois University Edwardsville: "siue",… } I am trying to find a way to retrieve the school name (key) based on the schoo ...

What is the best way to run tests on this asynchronous function using Jasmine?

My role in the service is listo: function () { var promiseResolved = $q.defer(); setTimeout(function () { promiseResolved.resolve(true); }, 2000); return promiseResolved.promise; } During my testing ...