Troubleshooting JavaScript If-Else Statements

Having a bit of trouble with my if else structure. When I enter the correct star name like "Vega", it incorrectly shows me "Error" instead of the expected result "Lyra".

Here's my code snippet:


var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var constellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];

function checkArrays() {
  for (n = 0; n < 7; ++n) {
      if (test.inputStars.value == stars[n]) {
          test.inputConstellations.value = constellations[n];
      } else { 
        test.inputConstellations.value = "Error"; 
      }
  }
}
    
<!DOCTYPE html>
    <html>
    <head>
    <title> Array structures</title>
    </head>
    <body>
    <form name="test">
    <input type="text" name="inputStars">
    <input type="button" onclick="checkArrays()" value="Find constellation">
    <input type="text" name="inputConstellations">
    </form>
    </body>
    </html>
    

Answer №1

One issue arises during the execution of the for loop: the value of test.inputConstellations.value gets replaced even if a match was found earlier in the program. The fix for this is to use the break statement:

if(test.inputStars.value==stars[n]){
    test.inputConstellations.value=constellations[n]
    break
}else{
    test.inputCostellations.value = "Error"
}

var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var costellations = ["Ursu Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];
function Arrays() {
    for (n = 0; n < 7; ++n) {
        if (test.inputStars.value == stars[n]) {
            test.inputCostellations.value = costellations[n];
            break
        }else{ 
          test.inputCostellations.value = "Error"; 
        }
    }
}
<!DOCTYPE html>
    <html>
      <head>
        <title> Array structures</title>
      </head>
      <body>
        <form name = "test">
          <input type = "text" name = "inputStars">
          <input type = "button" onclick ="Arrays()" value = "Find costellation">
          <input type = "text" name = "inputCostellations">
    </form>
  </body>
</html>

Answer №2

To ensure a default value for a variable and modify it when necessary, you can follow this approach:

var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var constellations = ["Ursa Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];

function ModifyArrays() {

    test.inputConstellations.value = "Error"; 
    for (n = 0; n < 7; ++n) {
        if (test.inputStars.value == stars[n]) {
            test.inputConstellations.value = constellations[n];
        }
    }           
}

Additionally, incorporating the 'break' statement can be helpful in certain scenarios:

var stars = ["Polaris", "Aldebaran", "Deneb", "Vega", "Altair", "Dubhe", "Regulus"];
var constellations = ["Ursa Minor", "Taurus", "Cygnus", "Lyra", "Aquila", "Ursa Major","Leo"];

function ModifyArrays() {

    test.inputConstellations.value = "Error"; 
    for (n = 0; n < 7; ++n) {
        if (test.inputStars.value == stars[n]) {
            test.inputConstellations.value = constellations[n];
            break;
        }
    }           
}

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

Grouping geoJSON data on Mapbox / Leaflet

I am currently in the process of setting up a clustered map on mapbox, similar to the example shown here: At the moment, my point data is being extracted from MYSQL and then converted into GeoJson using GeoPHP. You can view the current map setup here. I ...

What advantages can be gained by opting for more precise module imports?

As an illustration, consider a scenario where I have an Angular 6 application and need to bring in MatIconModule from the @angular/material library. Two options could be: import { MatIconModule } from '@angular/material/icon'; Or import { Mat ...

Executing password validation on login/register form using Node.js and EJS

In order to demonstrate a simple login page, I have created a form that requests typical information like username, password, etc. Additionally, it prompts the user to confirm their password, and if the lengths do not match, an error is triggered to notify ...

Sending a parameter value from a blade view in Laravel to a controller: tips and tricks

What is the best way to pass the value "{{$ item-> id}}" to a method in a controller? For example, if we have show.blade.php with the value: "{{$ item-> id}}" In MyController.php, how can we utilize this value within the method: public function ...

Modify the data displayed on the chart by choosing the desired year from the dropdown options

In my Angular app, I am showcasing a chart that visualizes data based on selected starting and ending years from dropdown menus. The X axis represents 18 cities, while the Y axis displays "IAP" values. To calculate the "IAP" values for each city within the ...

Unable to Access Browser Page

After printing out the URL in the console, I encountered an issue while trying to retrieve it using browser.get(). The error message displayed is as follows: Failed: Parameter 'url' must be a string, not object. Failed: Parameter 'url&apo ...

Discover the power of EJS embedded within HTML attributes!

There are two cases in which I am attempting to use an EJS tag within an HTML attribute. SITUATION 1: <input style="background-image: url(<%= img.URL %>)" /> SITUATION 2: <input onchange="handleCheckboxChange(<%= i ...

Why is it that PHP is used to retrieve the database value, JavaScript increments it, and AJAX saves it back to the database, yet it resets to 0.0 upon page refresh?

I am in the process of creating a page for setting temperature targets. The form allows users to adjust the target temperature by increments of 0.5 using JavaScript buttons. Once the user is satisfied with the new target, they can click 'set' whi ...

monitor the location of a div within a textarea

My question revolves around a textarea that is linked to a draggable div through the following code: $('#content').children().draggable({ drag : function () { $('#textarea').text("left:" +($(this).position( ...

Table header containing the weekdays for a jQuery calendar display

I need some assistance in creating a basic monthly calendar using a table. Check out this demo: www.jsfiddle.net/pzdw0s2n/1/ ...

Exploring the functionality of utilizing dual loops with v-for in Vue.js

I am facing an issue with my table code where I need to repeat it 6 times to match the day column above. I would like to use v-for and make use of a variable called "count" which represents the number of days. Can someone assist me with this task? <tabl ...

Passport sessions do not retain persistence

Having some trouble implementing OAuth 2.0 login where the sessions don't persist after authentication is a common issue. Additionally, there seems to be a problem with the app getting stuck in the routes/bnetauth.js file during the redirect in the ca ...

Enable Class exclusively on upward scrolling on the browser

Is there a way to dynamically change the class of an element only when the user scrolls the browser page upwards? Issue Filide>> JavaScript $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll <= 100) { ...

Is foreach not iterating through the elements properly?

In my code, I have a loop on rxDetails that is supposed to add a new field payAmount if any rxNumber matches with the data. However, when I run the forEach loop as shown below, it always misses the rxNumber 15131503 in the return. I'm not sure what I ...

Is there a way to ensure the content of two divs remains aligned despite changing data within them?

Currently, I have two separate Divs - one displaying temperature data and the other showing humidity levels. <div class="weatherwrap"> <div class="tempwrap" title="Current Temperature"> ...

Convert the value of the <textarea> element to HTML encoding

Is there a way to fetch the most recent updated value entered in a textarea and encode it in HTML format? I usually use this code snippet to retrieve the value: $('textarea').val(); // works consistently across browsers However, if the value c ...

tracking scroll position within div on main page

I have a div tag enclosed within a content tag due to the implementation of a masterpage containing the forms and body tags. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server"> <div id="xxx" style="overflow:s ...

The Javascript setTimeout Function Prolongs Its Operation

Currently, I have a web app index page that performs two main tasks. Firstly, it geocodes the user's location and stores it in a JavaScript variable called "variableToSend." Secondly, it sends this data to mySQL using a PHP script after a delay of 10 ...

Updating state atoms in Recoil.js externally from components: A comprehensive guide for React users

Being new to Recoil.js, I have set up an atom and selector for the signed-in user in my app: const signedInUserAtom = atom<SignedInUser | null>({ key: 'signedInUserAtom', default: null }) export const signedInUserSelector = selecto ...

What is the process for adding to a highly nested array in mongoose?

Here is the Model I am working with: const MessagesSchema = mongoose.Schema({ //for individual message text: { type: String, required: true } }, { timestamps : true }) const MessagesCollectionSch ...