Challenges with using JavaScript arrays

I'm facing a major issue with my website. As someone who is new to JavaScript, I am attempting to utilize an array for storing different responses based on the input provided in a text box. The template I am working with can be found here.

Although the code works perfectly without any modifications:

var answers = ["harry potter", "donald duck", "shrek", "supercoder"];

/*******************************/
//init() function
function init() {
    var myButton = document.getElementById("btnSubmit");
    myButton.onclick = registerName;
}
//assign init() function to onload event
onload = init;
/********************************************/
//registerName() function: it executes when user clicks the button
function registerName() {
    //set up main vars: Username entered by user,
    //a message string to communicate with the user,
    //a reference to the paragraph used to display the message,
    //and a boolean var (true/false) used as flag:
    //if the registration is successful, this is set to true,
    //if registration fails, this is set to false. It's initialized as false.
    //Notice how you chain getElementById(), value, and toLowerCase
    //to store the value entered by the user in lowercase
    var newName = document.getElementById("txtName").value.toLowerCase();
    var message = "";
    var result = document.getElementById("result");
    var success = false;
    var m1 = false;
    var m2 = false;
    ...
            ...
            ...

        }
        else if(newName == "a=30, b=30") {
            answers.push("m5");
            answers.push("m6");
            answers.push("m7");
            answers.push("m8");
            answers.push("m9");
            answers.push("s2");
        }
        if(success) {
            answers.push(newName);
        }
        //display Usernames sorted alphabetically on a new line
        result.innerHTML += "<br />" + answers.sort();
    }

However, after integrating the necessary if-else statements to include specific strings based on the input, the code stops functioning.

I understand that there might be something glaringly obvious that I'm missing.

Answer №1

Your section at the bottom with IF statements is causing some syntax errors due to incorrectly quoted values like "a=20, b=20" and "a=40, b=0". Make sure to fix these issues for proper functionality.

else if (newName == "a=20, b=20")
{
    answers.push("m2");
    answers.push("s1); <---

}

In addition,

else if (newName == "a=40, b=0")
{
    answers.push("m8");
    answers.push("s1); <---

}

Instead of

onload = init;

consider using

<body onload="init();">

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

Testing the Mongoose save() method by mocking it in an integration test

I am currently facing an issue while trying to create a test scenario. The problem arises with the endpoint I have for a REST-API: Post represents a Mongoose model. router.post('/addPost', (req, res) => { const post = new Post(req.body); ...

"Unraveling the Mystery of jQuery In

I am facing an issue with integrating jQuery into my code. I have always followed the same method, which has worked in the past, but now it seems to be causing problems for me. I suspect it may be because I am not on my usual laptop, although when I visite ...

Managing Jawbone API OAuth access tokens using node.js (express and passport)

Is there anyone who has successfully completed the Jawbone's OAuth2.0 authentication process for their REST API? I am facing difficulty in understanding how to access and send the authorization_code in order to obtain the access_token as mentioned in ...

The lineup includes ASP.NET, Java, Visual Basic, and AJAX

My ASP.NET application originally had a button that triggered VB.NET code execution on the server when clicked. Recently, there have been changes to the requirements and I've added a new menu that should replace the functionality of the old VB button ...

"Create a new row in the list by selecting an option from the drop-down

I'm experimenting with the following scenario. There is a function that reveals a hidden list based on a dropdown selection. To see it in action, please click here. What I am aiming to achieve is for Option1 to display the content of #List-Option1 ...

Updating the state within a component while specifically modifying the second item within a list

Currently in the process of constructing a battleShip game using React. Within my component, I have a state structured as follows: each coordinate is paired with a list containing two statuses - 'empty' indicating the absence of a ship ('bu ...

Error: Unexpected TypeError occurred stating that 'map' cannot be read from undefined, although the map method is not being used in the code

I have recently developed an Ethereum application for conducting transactions using React and the ethers module. Below, you can see a snippet of my code, specifically focusing on the function sendTransactions: import {ethers} from 'ethers'; impor ...

What is the process for generating a tree structure from an HTML element?

This particular element is found within my Vue2 application: <div class="child-elements-container draggable-container"> <div> <div entity-type="entitytype1" type="elementType" id="2" class= ...

Importance of body background color attribute

My CSS sets the body to a blue color, but my JavaScript changes the body color every second. It was working fine until I added a global CSS file. Unfortunately, I can't remove this CSS file because it contains many important rules that I need. I&apos ...

Transforming Json data into an Object using Angular 6

https://i.stack.imgur.com/JKUpL.png This is the current format of data I am receiving from the server, but I would like it to be in the form of an Object. public getOrder(): Observable < ORDERS > { return this._http.get < ORDERS > (`${thi ...

What is the best way to structure a data object in Javascript or VueJs?

As I work on developing a small application using VueJs, the data I receive is structured in a particular format: { "interactions":[ { "id":14, "user_id":1, "schedule":"2017-06-04 05:02:12", "typ ...

Using TypeScript to automatically determine the argument type of a function by analyzing the return type of a different function

I am working on an interface with the following structure: interface Res<R = any> { first?(): Promise<R>; second(arg: { response: R }): void; } However, I noticed that when creating a plain object based on this interface, the response ...

Issues encountered in loading JavaScript with jQuery script

I am facing an issue with my jQuery script not loading correctly. When I click on the calculate button, nothing happens as expected. I made sure to copy and paste jQuery directly into the file for offline use, and also created a personal console due to res ...

Facing an issue with AngularJS where I am able to retrieve data.data, but struggling to assign it to a scope variable

Currently, I am developing a website using AngularJS that retrieves questions and multiple-choice answers from an Amazon Web Services table. This data is used to dynamically create a prelab questions page. The http get request is functioning properly; when ...

PrimeFaces Issue with Redirection

Hello everyone, I am currently dealing with a redirection issue. Basically, I have an API that gets triggered when a user clicks on an image. This API captures the user's contact number and initiates a call through the software. Everything is functi ...

Converting PHP textfile content into an array

I need to process the $data variable which looks like this: $data = [ 'name' => $name, 'student_id' => $student_id, ]; and I would like to store it in a text file: $path = storage_path(& ...

Retrieve a collection of objects stored as a JSON array in React.js

I am new to working with React.js and I am encountering an issue while trying to access a specific index in an array of objects. Although I can successfully log the full "metrics" Array, attempting to access a specific index results in an error message sta ...

Steps for extracting a specific portion of a value contained within an attribute

In my code, there are multiple hyperlinks with different values attached to an onclick function. Here is an example: <a onclick="Utils.decideOffer('', {'unlockFeature': 'cars'});">cars text</a> <a onclick="Util ...

"Error in react-three-fiber: Only the last mesh retains its model, all others are

Currently, I am working on a React application where I am using react-three-fiber to visualize data in a 3D environment. My goal is to create various models by passing data representing their characteristics as props into components. However, I am encounte ...

NodeJs and Mysql query execution experiencing significant delays

NodeJs + Mysql query delays and execution timing issue https://github.com/mysqljs/mysql Hello everyone, I'm facing a problem with mysql js. Whenever I use .query(), the callback is taking too long to execute and returning empty results. However, if I ...