What's a great way to verify various conditions in if/else statements?

Attempting to create an if/else statement that dynamically generates HTML content based on the option selected by the randomNumber function from the myOptions array. Struggling with checking the if condition, as it consistently falls into the else block displaying "You lose!...".

Aim: Options 1 and Options 2 result in a win, while Options 3 and Options 4 lead to a loss.

Check out the code snippet here.

function randomNumber(range) {
    return Math.round( Math.random() * range );
}

var myOptions = ["Option 1", "Option 2", "Option 3", "Option 4"];
myOptions = myOptions[randomNumber( myOptions.length - 1)];
alert(myOptions);

if (myOptions <= 1) {
    document.getElementById("message").innerHTML = "You win!";
} else {
    document.getElementById("message").innerHTML = "You lose! " + myOptions + " was your choice";
}

Answer №1

Ensure that you are not using the same variable for both your array of options and the randomly selected option. Assign a random index number first, and then refer to the corresponding value in the array when needed.

In your previous code, you were replacing the entire option array with one of its values, and then attempting to compare this string value to a numerical value. While it is possible to simply assign myOptions as a string and check its value for winning, I believe you intend to accomplish something like the following:

var myOptions = ["Option 1", "Option 2", "Option 3", "Option 4"];

var optionIndex = randomNumber(myOptions.length);
var selectedOption = myOptions[optionIndex];

alert(selectedOption);

if (optionIndex <= 1) {
    document.getElementById("message").innerHTML = "You win!";
} else {
    document.getElementById("message").innerHTML = "You lose! " + selectedOption + " was your choice";
}

Answer №2

It seems like you're running a check to see if myOptions <= 1. Remember that myOptions will always be a string with one of the specific values, not a Number.

Here is the updated link for the jsfiddle: http://jsfiddle.net/abcdef12345/20/

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 possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object. Interface: export interface PhotoToCreate { albumName: string; albumTitle: string; ImageNameO : string; imageNameT : string; } Component import { Component, OnI ...

A C program that reads a file and counts the number of words specified in an array

My goal is to analyze a text file containing a paragraph, locate specific words (which are defined and stored in an array), and then generate a new file displaying the frequency of each word. The desired output format would look something like this, system ...

Automate Facebook Photo Untagging using JavaScript

After spending hours working on it, I want to create a JavaScript routine that can automatically untag me from photos on Facebook. My plan is to run this in the Firebug console so I can untangle myself from all Facebook photos, as there's no way to do ...

Counting the number of key-value pairs for a specific key in a JSON data can be achieved by implementing

Is there a way to determine if __metadata and ItemToEkbeNav are the root elements for their children who have key-value pairs? I've attempted various methods such as Object.keys().length and Array.isArray(), but haven't been able to retrieve the ...

Sending an array from a view to a controller via AJAX in Codeigniter

As a newcomer to web programming, particularly in the realm of Codeigniter, I am currently seeking guidance on how to successfully pass an array from a view to a controller. Below is a snippet of the HTML script in my view: <tr class="rowdim"> < ...

What is the best method for including a column that utilizes an aggregate function in the main table within a case statement?

Whenever I run this query, I encounter the following error message: "#1111 - Invalid use of group function" SELECT c.`id_c`, week(date) AS `week`, YEAR(date) AS `year`, COUNT(mood) AS `moodNumber`, AVG(mood) AS `moodAverage`, IF(COUNT(mood) > 2, ...

Updating the default value of a MUI TextField: Step-by-step guide

I am in the final stages of completing my form, but I have encountered an issue when trying to display the current user's name in the defaultValue variable of the TextField from MUI. If the value starts as ""/null, or essentially empty, the ...

Issue with the intersection of mouse and camera rays in three.js

I've been working on a simple program that involves creating a clickable 3D object in Three.js. I've referenced my code from When I click directly on the object, it works as expected, but upon examining the resulting array, I noticed that the ob ...

Utilizing array.filter() to retrieve objects with values containing specified keywords

In my node.js project, I have an array named products that is structured as follows: [ { product_id: 'adidas-training-shoes', title: 'Adidas Training Shoes', description: 'description', brand: 'brand&a ...

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 ...

Techniques for capturing Django's output from an Ajax request

I've been trying to utilize Ajax for converting my form data to JSON and sending it to my Django view. However, I'm encountering an issue where after successful processing in the view, I am returning a template response with some context data tha ...

Attempting to add my first contribution to the Ruby project on GitHub - a brand new Array class instance method

I recently provided a detailed answer to a question on this platform concerning deleting elements from an array in Ruby. As I was writing my response, I realized that the method I came up with could potentially enhance Ruby's functionality. This promp ...

Is it possible to use "/path/{?}" in a path when working with Node.js?

I am new to node.js and I'm working on creating a route that will verify the authorization of all users when the specified endpoint begins with /api. I've learned that an optional value can be indicated using ? like {_id?}, but is it possible to ...

Deliver the Stripe API response from the backend to the frontend page

I'm struggling to retrieve the response object from Stripe after creating a subscription using npm. import Stripe from 'stripe'; const key = require("stripe")("XXXXXXXXXXXXXXXXX"); export function subscribe(cus, items) { key.subscription ...

Adding an operation to a function that is linked to an event

On one of my pages, I have a button that triggers some ajax calls with data binding. The binding code is generic and used in various parts of the application, so altering its behavior could impact other users. However, I now have a specific requirement fo ...

HTML: Efficiently updating multiple cell contents in a large table using jQuery or JavaScript

Hello, I am currently working on developing an HTML page that consists of a large data table. My goal is to have the data in the table update dynamically as the user interacts with various controls on the page, without having to reload the entire page. ...

What could be causing the multifiles uploader to fail in uploading files?

I have been attempting to create a multiple files uploader with sorter connected to a database on my website. However, whenever I try to upload some files, the uploader sends me several notices. Notice: Undefined index: media in /var/www/mediasorter/mediau ...

The JQuery pagination feature fails to function properly once an AJAX load is initiated

I am using jspages.js to implement pagination with jQuery. Everything works fine when the page is initially loaded. However, I encounter an error when the content for pagination is loaded after an ajax call. The plugin does not seem to work as expected. ...

Confirm that the input value consists of x numeric characters

Looking to validate an input field that must contain a minimum of x amount of numeric characters. For example, let's say I require the input value to have at least 5 numeric characters: 12345 - valid AB12345 - valid 123456 - valid AB312312 - valid a ...

Assigning an "active" class and URL attribute to a link based on the metadata of the current page

I have three pages, each featuring a navigation bar with three links: <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="/home">Home</a> </li> <li class="nav-item"> <a class ...