The JavaScript if statement does not appear to be accurate

I am encountering issues with my if, else, and else if statements.

Here is the code snippet in question:

function draw(d) {
    var testarray = JSON.parse(a);
    var testarray1 = JSON.parse(a1);
    var testarray2 = JSON.parse(a2);

    var Yaxis = $("#<%=hidden10.ClientID%>").val();

    if (d == 1)
    {
        var c = testarray;
        Yaxis = 'data';   
    }
    else if (d == 1)
    {
        var e = testarray1;
        Yaxis = 'data1';
    }
    else if (d == 2)
    {
        var c = testarray;
        Yaxis = 'data2';
    }
    else if (d == 2)
    {
        var e = testarray1;
        Yaxis = 'data3';
    }
    else(d == 3)
    {
        var e = testarray1;
        Yaxis = 'data4';
    }

During debugging, it seems that the code only recognizes d==1 and then jumps to d==3 without executing for 1 and 2. The values of yaxis only show up as data4, omitting data, data1, and data2 on the graph.

The issue might be related to the incorrect implementation of my else statement. I have referred to a resource about JavaScript conditionals but still couldn't resolve it.

d corresponds to a radio button fetched from the VB.NET backend:

Select Case RadioButtonList1.SelectedItem.Value
    Case 1


        Dim Yaxis As String
        If RadioButtonList1.SelectedItem.Value = 1 Then
            Yaxis = "data"
        End If

        hidden10.Value = Yaxis

        For Each row In Year1
            testarray.Add(row("kWh"))
        Next row

        Dim arrayJsonTest1 As String = serializer1.Serialize(testarray)
        Dim arrayJson11 As String = serializer1.Serialize(testarray1)

        hidden.Value = arrayJsonTest1
        hidden1.Value = arrayJson11
        hidden2.Value = arrayJson12

        ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, "draw", "javascript:draw(1);", True)

Answer №1

            if (d == 1)
                           {
               var c = testarray
               Yaxis = 'data';

          }

          else if (d == 1)//why is this same?
          {
              var e = testarray1
              Yaxis = 'data1';
              }

if and else if are both checking the same condition. This needs to be corrected.

               if (d == 1)
               {
               var c = testarray
               Yaxis = 'data';
              var e = testarray1
              Yaxis = 'data1';
              }
              else if(d == 3)
              {
              var e = testarray1
              Yaxis = 'data4';
              }

Answer №2

The most critical issue in your code lies towards the end:

       else (d == 3) 
       {
           var e = testarray1
           Yaxis = 'data4';
       }

In this part, you are not using an if statement properly; hence, the JavaScript parser interprets it as follows:

       else true;

       {
           var e = testarray1
           Yaxis = 'data4';
       }

Essentially, (d == 3) is evaluated as true, followed by another block of code that updates the value of

Yaxis</code independently of the preceding <code>if ... else
block.

A cleaner approach would be to utilize the switch statement instead:

switch (d) {
    case 1:
        Yaxis = 'data';
        break;
    case 2:
        Yaxis = 'data1';
        break;
    ... etc .. 
 }

Note that variables like 'c', 'e' are defined within the brackets and their values won't be accessible outside.

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

How to style the first dropdown value in AngularJS to appear bold?

Is there a way to style only the first value in a dropdown list as bold without using jQuery? Here is the code for the dropdown: <div class="col-xs-3"> <select-box id="ad-version-select" options="curItem.stats.version" model="state.version" i ...

Update the link to a KML file used by Google Maps when a button is clicked

On the initial page load, I want to showcase an 8 Day Average KML file on Google Maps. However, users should have the option to click on the "1 Day" and "3 Day" buttons to switch the reference in Google Maps from the "8 Day" file. The aim is to design a s ...

Convert an object to a custom array using JavaScript

I need to transform the following object: "age": [ { "Under 20": "14", "Above 40": "1" } ] into this structure: $scope data = {rows:[ {c: [ {v: "Under 20"}, {v: 14} ]}, {c: [ {v: "Above 40"}, ...

Google Scripts: Generating a set of data to include in an email

As a newcomer to Google Script and JavaScript, I'm on a mission to email a list of file names extracted from a spreadsheet. The names reside in a column within my sheet, and after defining a variable called "newfiles" to cherry-pick only the necessary ...

Create a collection of data by retrieving values from a web service response

My goal is to populate table values from a webservice response. The issue arises when the response format is not compatible with the table. The response structure may vary. 0:{name: "image.png", base64: "iVBORw"} 1:{name: "download.png", base64: "iVBO"} 2 ...

The console does not display the JSON data for requests and responses

I have successfully set up a server inside of VSCode, but unfortunately the request and response logs that I usually see in my terminal when running the server with npm start are not appearing. I would really like for them to display in the Debug Terminal ...

Combining AngularJS with Servlets: A Seamless Integration

I am attempting to retrieve a JSON object from a servlet by calling a function through a link in my HTML code. Below is the HTML link that calls the fTest function: <td><a href="" ng-controller="minaplantaCtrl" ng-click="fTest(x.id_camion_descar ...

The code functions perfectly on JSfiddle, but for some reason it halts when implemented on

Unfortunately, the code that was working perfectly on JSfiddle seems to be encountering issues when implemented on a regular HTML site. The content loads fine but there seems to be an error with the preview function after selecting an image. We have colla ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

Utilize Angular to transform a standard text string within a JSON object into a properly formatted URL

Welcome to my first Stack Overflow question! I usually find the answers I need on my own, but this time I could use some guidance as I delve into Angular. I have a directive that pulls the name and URL from a JSON object and generates HTML with the name a ...

Sending an AJAX request to a REST service in order to submit the information captured in an HTML form

<html> <body> <form method="POST"> <label>username</lable> <input id="username" name="username" type="text"> <label>emailid</lable> <input id="emailid" ...

The NodeJS program fails to authenticate the Google Calendar API integration, resulting in an undefined response even when valid credentials and tokens are provided

I am seeking assistance with my Google Calendar API integration in NodeJS. I am encountering an error message indicating that the daily limit for unauthenticated use has been exceeded, requiring signup for continued usage. Despite researching this issue on ...

Retrieving parameters from a class that is handed over from the constructor to a function by leveraging the rest parameter feature

I am encountering an issue where the Method is not reading the values in the arguments, despite my attempts to pass each argument through the constructor into the method for encryption. Could someone please point out what I might be doing wrong? class A ...

Using Javascript libraries on a Chromebook: A comprehensive guide to getting started

Doing some coding on my chromebook and wondering if it's possible to download and utilize libraries such as jQuery. Would really appreciate any assistance with this! ...

What is the best way to trigger an ajax request when a user selects a tab?

How can I trigger an ajax call when a tab is clicked by the user? What is the best way to handle the HTML response and display it within the tab? How do I bind JavaScript events to the dynamically loaded HTML content? I am familiar with using jQueryUI tab ...

Tips for preserving an HTML dynamic table in a database

I have a challenge where I am generating a dynamic HTML table using javascript. What is the best way to store this dynamic HTML table in a database using CodeIgniter? This is the code snippet for my input form: <table id="tb3" name="tb3"> & ...

What could be causing the lack of response from XMLHttpRequest?

I am attempting to retrieve results from a PHP file that is connected to a database. However, the variable being sent to the database is not being sent from the XMLHttpRequest. Below is the HTML code: <input type="text" id="name"/> Here is the cor ...

What is the best way to select or deselect all asp.net checkboxes with just one checkbox event?

I am looking for a way to control the checkboxes on my webpage using a checkbox named Select All, allowing me to check or uncheck all checkboxes within individual div sections. Since my checkboxes are asp.net controls with runat=server, I am unsure how to ...

Unable to wrap the strings from the database in a span element

I have a challenge where I need to enclose the first and last strings that represent the title and price of a product within a div using a span tag. These strings are dynamic, sourced from a database, and differ for each product. I have attempted to use th ...

Using Socket.IO in Node.js to distribute information to every connected client

Currently, I am in the process of developing a WebGL multiplayer game. My approach involves using socket.io and express in node.js to enable multiplayer functionality. However, I am encountering an issue with broadcasting key events. When a user presses a ...