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

Error Encountered During JavaScript Form Validation

Currently, I am troubleshooting a website that was created by another developer. There is a form with JavaScript validation to ensure data is accurately entered into the database. However, I am puzzled as to why I keep receiving these alert messages. Pleas ...

Attempting to call a nested div class in JavaScript, but experiencing issues with the updated code when implemented in

Seeking assistance. In the process of creating a nested div inside body > div > div . You can find more information in this Stack Overflow thread. Check out my JSFiddle demo here: https://jsfiddle.net/41w8gjec/6/. You can also view the nested div on the ...

Ways to direct to a specific div upon clicking an anchor tag following a page reload?

<a href="#goto">Link 1</a> <div id="goto">DIV</div> Whenever I click on the anchor tag, my webpage reloads and displays a new div with the ID of goto. This div was previously hidden but is now visible at the bottom of the page. I ...

What sets declaring variables apart in Vue?

Can you clarify the distinctions among various methods of declaring variables? When should I employ each of these declaration methods? <script> const someVariable = 12345 export default { name: 'App', } </script> <script> e ...

Adding a character to an AngularJS textbox

I am attempting to add the "|" Pipe symbol to a textbox when a button is clicked, using this function. $scope.appendPipe = function(){ var $textBox = $( '#synonyms' ); $textBox.val($textBox.val()+'|'); //textBox ...

Implement an event listener on the reference obtained from the React context

Within the React context provider, a ref is established to be utilized by another component for setting a blur event listener. The issue arises when the blur event fails to trigger the listener. The following is a snippet of code from the context provider ...

Steps for assigning innerHTML values to elements within a cloned div

Currently, I am setting up a search form and I require dynamically created divs to display the search results. The approach I am taking involves: Creating the necessary HTML elements. Cloning the structure for each result and updating the content of ...

Tips for configuring Visual Studio Code to utilize path mappings for handling automatic imports

In order to streamline my project and avoid messy paths, I am implementing absolute paths that will allow for consistent imports regardless of the file's location in the project tree. For this purpose, I made adjustments to the tsconfig.json: "paths ...

Issue with xsl:include functionality in a Firefox extension

I've been working on a Firefox extension that utilizes XSL transformations with no issues. However, I encountered a problem when trying to perform an xsl:include from the XSL stylesheet. Upon importing the XSL stylesheet containing an xsl:include stat ...

Display a single submenu on mouseover using Javascript

Hello there, I have been working on creating a small menu using only Javascript, but I am facing an issue where the onmouseover event is displaying all submenus instead of just one. Below is the section of code that is supposed to change style.display to ...

Is there a way to programmatically click on an href link in Firefox? The method that is typically used in Internet Explorer

http://jsfiddle.net/HVGre/1/ - check out this test link. I have a link in my HTML code that needs to be clickable dynamically. While it functions well with the .click() method in Internet Explorer, it fails in Firefox. Unfortunately, changing the link to ...

React splits the page and interrupts the scroll event listener

For some reason, my webpage has been split by the React.js library. When attempting to scroll down while hovering over the top navigation menu, scrolling becomes impossible. However, scrolling works fine when done on any other part of the screen. I' ...

Strategies for Managing Output Event Prioritization in Angular Using RxJs Based on Trigger Sequence

Within my Angular Application, there is a widget with two event outputs originating from a third-party library. Unfortunately, I am unable to modify its behavior. <myWidget (onAlwaysEvent)="onAlwaysEvent($event)" (onSometimesEvent)="onSometimesEven ...

Show information in a React Native element | Firebase

Just starting out with react native and struggling to display data in a component? You're not alone! I'm having trouble too and would love some guidance on how to destructure the data for display. Any tips? import React,{useState,useEffect} from ...

Troubleshooting: Vue.js custom select element not responding to blur event

Unique Scenario A custom autocomplete select component has been created that not only autocompletes but also allows for adding a new value if the result is not found. This functionality was discovered to be missing in the vue-select module. Explore the C ...

What are the benefits of using "var self = this" for synchronizing between a class and events?

Consider this straightforward code example (it's in AngularJS for simplicity, but the scenario is common in JavaScript): angular.module('app',[]). directive('myDir', function(){ this.state = {a:1, b:2}; return { l ...

What is the process for displaying information from a database on a model popup box?

I am working on displaying books in the Index view that are retrieved from a database. Each book has a button underneath it. The goal is to have a modal box appear when these buttons are clicked, showing details of the corresponding book such as the book i ...

Navigating a table while keeping headers in place at the top

Trying to construct a table where the thead remains fixed while the tbody scrolls. Utilizing percentages and fixed width for cell size determination, aiming for uniformity and alignment between percentage td's and thead headers. Referenced JSFiddle d ...

Using Node.js to send a response only after every promise has been resolved

I am currently working on a NodeJS Express route where I have encountered an issue. In this route, a function is called multiple times, each returning a Promise. The values from these Promises are then added to an Array and sent back to the client using re ...

Issues with the functionality of the jQuery notify plugin are being encountered when used in a

I am currently utilizing the jQuery notify plugin and have included all the necessary JS files in the header. However, whenever I attempt to call the $.notify function in another JS file that also involves AJAX, I encounter difficulty accessing the $.notif ...