I am struggling with correctly constructing the "if" statement

I need help with a function I'm trying to construct. The purpose of this function is to determine if the input provided by the user in the boxes is an integer or not, and then print out the appropriate commentary. However, I am encountering an issue at the second level of the function where the "if" statement is failing to check if figure1 is a number (it doesn't output anything), while the "else if" and "else" statements are working fine. Can someone please assist me in identifying what might be wrong with my function?

function show() {
  //Variable contains the value of field1 from input html which has been read thanks to onclick
  var figure1 = document.getElementById("field1").value; 
  //Variable contains the value of field2 from input html which has been read thanks to onclick
  var figure2 = document.getElementById("field2").value; 

  //empty until the instruction write in something
  let sign = "";

  //STEP 1
  //loop working until the value of i reach the value of figure2
  for (i = figure1; i <= figure2; i++) 
  {
    if (Number(figure1) && Number(figure2)) {
      //if both figure1 and figure2 are numbers, print the sign as follows - what sign contains from previous iteration + i + ", "
      sign = sign + i + ", "; 
      
    } else {
    
      if (Number(figure1)) {
        //If statements from "if" level above haven't been fulfilled, print "Please, type integer in right-hand box";
        sign = "Proszę wpisać liczbę w prawym polu"; 
        
      } else if (Number(figure2)) {
        //If statements from "if" level above haven't been fulfilled, print "Please, type integer in left-hand box";
        sign = "Proszę wpisać liczbę w lewym polu"; 
        
      } else {
        sign = "Proszę wpisać wartości liczbowe w obu polach";
        // If statements from "if"
        // level above haven 't been fulfilled, print "Please, type integer in both boxes";
      }
    }
  }
  //podmienia wartość diva o id result na wartość zmiennej sign.
  document.getElementById("result").innerHTML = sign; 
}
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="text" id="field1">
  <!--W tym polu umieszczamy liczbę z przedziału-->
  <input type="text" id="field2">
  <!--W tym polu umieszczamy liczbę z przedziału-->
  <input type="submit" value="pokaż" onclick="show()">
  <!--Po kliknięciu zostaje wywołana funkcja "show()"-->
  <div id="result"></div>
  <!--wnętrze diva podmienimy przy użyciu funkcji "show()"-->
</body>

Answer №1

Unable to provide a comment due to insufficient reputation, so I will express my thoughts through an answer.

Encountering 3 issues with the code snippet you provided:

for (i = figure1; i <= figure2; i++) 
  1. The main goal of the function is to validate if both figure1 and figure2 are numbers. However, by placing them in a loop as such, it assumes they are numbers already. Consider this - how can non-numeric values be incremented and compared within a for loop?

  2. You're assuming figure1 is always less than figure2. Is there solid reasoning behind this assumption? If incorrect, the loop will not run even once.

  3. Moreover, the necessity of the loop is unclear. If the objective is simply to determine if the inputs are integers or not, looping and altering their values seems redundant. A single check should suffice.

Address these concerns and verify if the issue persists.

Answer №2

Forget about it

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Document</title>

    <script type = "text/javascript">

        function display()
        {
            var number1 = document.getElementById("num1").value;
            var number2 = document.getElementById("num2").value;

            let output = "";

            if (Number(number1) && Number(number2))
            {
                for (i=number1; i<=number2; i++)
                {
                    output += i + ", ";
                }

                for (i=number1; i>=number2; i--)
                {
                    output += i + ", ";
                }
            }
            else if (Number(number1))
            {
                output = "Please enter a numerical value in the right field.";
            }
            else if (Number(number2))
            {
                output = "Please enter a numerical value in the left field.";
            }
            else
            {
                output = "Please enter numerical values in both fields.";
            }

            document.getElementById("result").innerHTML = output;
        }

    </script>
</head>
<body>

    <input type="text" id="num1">
    <input type="text" id="num2">
    <input type="submit" value="display" onclick="display()">

    <div id="result"></div>

</body>
</html>

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

"Exploring the creation of multidimensional arrays in Arduino - what steps should I

Is there a way to create a multidimensional array in Arduino? I want something like this. C++ var arr = { name: "John", age: "51", children: [ "Sara", "Daniel" ] }; or maybe like this. JSON ...

Amazon Banner Integration for Angular Version 4

Having some trouble getting an Amazon banner to display inside an angular material 2 card. The div appears empty and the banner is not rendering. Any idea what could be causing this issue? Below is the code snippet showcasing my attempts: <md-card clas ...

Unable to locate a contact within the state

Currently, I am diving into the world of React by exploring its documentation and challenging myself to build a small chat application. While I have a good grasp on the basics, I am encountering some issues with states. Within my code, there is an object ...

Customize your file input with Bootstrap 4 using bs-custom-file-input and create a Symfony 5 collection with dynamic upload fields

The issue of not having a label for the chosen filename in a bootstrap 4 upload field has been resolved using the plugin https://github.com/Johann-S/bs-custom-file-input You can utilize "bs-custom-file-input" to showcase the selected filename in the boots ...

The error message "Babel - Unable to access property 'TYPED_ARRAY_SUPPORT' of an unspecified object" is being displayed

Encountering a recurring error when using the oidc-client library in my React project. The error message reads: Babel - Cannot read property 'TYPED_ARRAY_SUPPORT' of undefined Despite knowing about the Redux implementation of this library, I ...

I am only able to trigger my AJAX request once

Whenever I click on a checkbox, an ajax function is triggered. This function sends a query string to a PHP script and returns relevant HTML. Strangely enough, if I first select a dropdown option and then check another checkbox along with the previous one ...

Javascript Developer Platform glitches

Describing this issue is proving difficult, and I have been unable to find any solutions online. My knowledge of Javascript and its technologies is still quite new. I am currently working on a web application using NodeJS, Express, and Jade that was assig ...

Combining string values from arrays of varying lengths in JavaScript

Here are two arrays I am working with: The first array (Array1) contains the elements: arr1 = ["Precon", "Contra", "Postco", "Cancel", "Consul"] The second array (Array2) contains the elements: arr2 = ["EJID", "EMBA", "EMPR", "GOBI", "PART", "PPOL", "S ...

Animating scrollTop using jQuery is a useful feature for creating

I am facing an issue with several section tags within a div that has overflow set to hidden. The structure of the code is as follows: <div id="viewport"> <section> content </section> <section> content </ ...

What is the best way to create a loop with JSON data?

My challenge is to showcase json data using a loop. I have received the following results, but I am unsure of how to display them with a loop. [ {"latitude":"23.046100780353495","longitude":"72.56860542227514"}, {"latitude":"23.088427701737665"," ...

Utilize JavaScript code from an npm package to incorporate its functionality within your program

I have recently integrated the htmlhint library into my development workflow. I am able to execute it via the command line on any HTML file using the following command: npx htmlhint src/test-file.html Upon running this command, the file is linted and any ...

Is there a way to configure eslint to recognize and allow the nullish-coalescing assignment syntax?

The "nullish-coalescing assignment" operator, ??=, has been around for some time now in JavaScript. However, it appears that even newer versions of eslint, like 8.38.0, do not seem to recognize it and throw a syntax error regarding the assignment ...

What is the best way to display multiple quotes from my generator at once?

I'm seeking assistance with my quote generator. It functions correctly in JS Bin, generating the specified number of quotes when output to the console log. However, once integrated into an HTML page, it only generates one quote regardless of user inpu ...

How can I create a menu of buttons in Vue that open individual windows with unique URLs when clicked?

Javascript Code: function InitializeVue() { var vueOptions = { el: '#activeEvents', data: { activeEvents: [] } }; vueInstance = new Vue(vueOptions); } HTML Code: <table id="activeEvents"> ...

Error encountered: jQuery version 1.8.0 reports a syntax error due to an unrecognized expression containing ">" symbol

After adding jquery to my website, I encountered an issue with the jQuery 1.8.0 error: Error Message: Syntax error, unrecognized expression: &gt; Can someone please assist me with this problem? ...

Information stored in IndexedDB is not retained permanently

My journey to explore various web technologies (such as HTML, CSS, JavaScript) led me to create a simple web application. To enhance the functionality of my app, I integrated IndexedDB for data storage and operations like insert, update, get and delete. H ...

How to toggle the visibility of checkboxes in JavaScript based on their checked status

I am facing an issue with some checkboxes as I am unable to filter them based on whether they are checked or not. The concept is simple. When I click on "All", all the checkboxes should be displayed. However, when I click on "Selected", only the selected ...

Attempting to abbreviate repetitive Javascript instructions

I have this functional javascript code, but I feel like there might be a more efficient way to write it. Any suggestions on simplifying this? let searchTerm = 'Some search text'; const isMatch = entry.title.toLowerCase().includes(searchTer ...

How to achieve a reverse slideToggle effect with jQuery when refreshing the page

After creating a custom menu on Wordpress using jQuery slideToggle to toggle dropdown on hover, everything seemed to be working perfectly. However, I noticed that when I refreshed the page while moving my cursor between two menu items with dropdown menus, ...

Unraveling the mystery: Retrieving data from various child components within a Vue parent component

Currently, I am in the process of constructing a view that includes a primary component called ContentComponent. This component acts as a container for a series of sub-components, each representing a form module. The list of forms include: EvaluationForm ...