The "else" statement is never being executed

Trying to create a form where users enter their first name, last name, and city. If any input is empty or contains numbers, a message should appear requesting to fill out all boxes without numbers. Otherwise, display a personalized quote using the input information. However, the else statement is not functioning as expected.

I attempted to modify the code and switch some variables around.

function FillInfo()
{
         /* variables */
         var firstName = document.forms["SignUpForm"]["firstName"].value;
         var lastName = document.forms["SignUpForm"]["lastName"].value;
         var city = document.forms["SignUpForm"]["city"].value;
         /* Check if input fields are empty or contain numbers */
         if(firstName=="" || !isNaN(firstName) || lastName=="" ||  !isNaN(lastName) || city=="" || !isNaN(city){  

            document.getElementById("info").innerHTML = "Please fill out all available boxes and ensure no numbers are included";    
      }
         else{     

            document.getElementById("info").innerHTML =  "Thank you" + " " + firstName + " " + lastName + " from" + " " + city + "." + " " + "You are now being considered as our next adventurer. Good luck!";
    }
 }
<div class="heading2">
        <div class="container2">
            <p>Ready for a space travel adventure? Fill out our form!</p><br>
            <form name="SignUpForm">
                <input type="text" name="firstName" placeholder="First name" required><br>
                <input type="text" name="lastName" placeholder="Last name" required><br>
                <input type="text" name="city" placeholder="City" required><br><br>
                <div id="info" class="well"></div>
                <input type="button" class="otherpage" onclick="FillInfo();" value="Submit" /><br><br>
                <a href="Homepage.html" class="BeginLink">Go back</a>
            </form>  
       </div>      
    </div>

Answer №1

Your conditional statement needs to be adjusted as it currently always resolves to true.

Instead of:

if (jmeno=="" || jmeno!=NaN || prijmeni=="" ||  prijmeni!= NaN || mesto=="" || mesto!=NaN) {

You should consider using:

if (jmeno==="" || isNaN(jmeno) || prijmeni==="" || isNaN(prijmeni) || mesto==="" || isNaN(mesto)) {

Keep in mind that NaN is never equal to NaN, so you should utilize isNaN instead.

However, the current code does not fit your actual requirements. You aim to verify the absence of number values, correct? Depending on whether you want to disallow any numbers or number-only entries, adjustments are necessary. For instance: use !isNaN(Number(jmeno)) to ascertain if the entry is a number-only value. Since data from text inputs is in string format, conversion becomes essential.

Answer №2

Your reasoning is flawed

name=="" || name!=NaN

This will always result in true, it seems like you intended

name=="" || isNaN(name)

Of course, the rest of the statement requires adjustments as well.

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

Issues with dependencies in npx create react app

After initiating a new react project with npx create-react-app client, I have encountered an issue where the react-scripts command is not found, preventing me from running the start script. Is there a way to resolve this problem? Furthermore, when attempt ...

Is it possible to use a shell script to replace the external CSS file link in an HTML file with the actual content of the CSS file

Seeking a solution for replacing external CSS and JS file links in an HTML document with the actual content of these files. The current structure of the HTML file is as follows: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C ...

Troubleshooting Issue with jQuery onclick Function not Transmitting Data

Why is this error occurring: Uncaught TypeError: Object [object global] has no method 'data' HTML: $attributes = array('class' => 'main post', 'onsubmit' => 'validateModules(event)', 'dataid& ...

Utilize jQuery to extract various input/select box values and compile them into an array for submission using .ajax()

I am currently facing an issue with dynamically generated forms using PHP and updated with jQuery's .appendTo() function as visitors interact with it. My main goal is to collect all input text and select box values from the current form and submit the ...

What alternative can be used for jquery isotope when JavaScript is not enabled?

Is there a backup plan for jQuery isotope if JavaScript isn't working? For instance, if I'm using the fitColumns feature, is there an alternative layout style available in case JavaScript is disabled, similar to what is seen on the new Myspace? ...

Outline along a single edge

Is there a way to add an inset border to an HTML element on just one side, without using an image as a background? I've been stretching and positioning images for this purpose in the past, but I recently discovered the outline CSS property. However, i ...

Creating dynamic visual elements on a webpage using HTML: Video

As I continue to learn HTML, CSS, and JavaScript to create a basic website for educational purposes, I have successfully embedded a video stored in my drive using the video element on an HTML page. However, I now aim to also display the video's title, ...

Leveraging the 'this' keyword in TypeScript

In my Javascript class, I used the 'this' keyword as shown below: if (this[this.props.steps[i].stepId].sendState !== undefined) { this.setState({ allStates: { ...this.state.allStates, [thi ...

Error: guild is not defined | discord.js

Having trouble with a ReferenceError that says guild is not defined? I recently encountered a similar issue with members but managed to fix it by adding a constant. As someone new to javascript and node.js, I could use some assistance. I've even tried ...

Using conditional CSS in React/Next.js

While using Next.js, I have implemented conditional rendering on components successfully. However, I am facing an issue where the CSS styles differ between different components. Code 1: import React from "react"; import Profile from "../../ ...

Obtaining a complete element from an array that includes a distinct value

I'm attempting to retrieve a specific item from an array that matches a given value. Imagine we have an array const items = ["boat.gif", "goat.png", "moat.jpg"]; We also have a variable const imageName = "boat" Since we don't know the file ex ...

Updating ng-table within an Angular controller

Having encountered an unusual issue with ng-table. Here is a snippet of code from my controller: this.category = "Open"; this.category = ["Open", "Accepted", "Rejected"]; this.dataItems = []; var _this = this; this.$scope.$watch("vm.category", function( ...

What is causing my AJAX Contact Form to navigate away from the original page?

I configured a contact form on my website more than 5 years ago, and I vividly remember that it used to show error/success messages directly on the page within the #form-messages div. However, recently, instead of staying on the contact form page and displ ...

When you hover over nested HTML-lists in a webpage, make the tree's long text lines expand gracefully using a combination of HTML, CSS

In my Angular 4 application, I have a left div that displays a tree of items as recursive HTML lists. When there is a long text, it gets cut off by the border of the div and a scrollbar appears. I want to have the text expand beyond the border and show in ...

Add information to the Database seamlessly without the need to refresh the page using PHP in combination with JQuery

Check out my code below: <form action='insert.php' method='post' id='myform'> <input type='hidden' name='tmdb_id'/> <button id='insert'>Insert</button> <p i ...

When items are removed client-side, the Listbox becomes null

Given a Web Forms project inherited by me, I am relatively new to the field of Web development. The page in question features 2 listboxes: lstCaseLoad, containing "Caseloads" (ID numbers), and lstAssignedCaseLoad, filled with Caseloads chosen by the Form U ...

Implementing Node.js with browser cache and handling 304 responses

I am currently in the process of creating a single page application with a standard HTML layout as shown below: <html> <head> <title>...</title> <link rel="stylesheet" media="all" type="text/css" href="css/main.css"> ...

Using Google Script Code in Sheet to input a key and click on the submission button

Is there a way to enable using the Enter key in addition to clicking the submit button to input data and save it to a cell? I'm having trouble getting my current code to work. Any suggestions on how to modify it? <script> var itemBox = document ...

Is it possible to include parameters in an HTML GET request with Electron.Net?

I have successfully implemented a function in an Angular component within an Electron application using HttpClient: var auth = "Bearer" + "abdedede"; let header = new HttpHeaders({ "Content-Type": 'application/json&a ...

Using React Typescript to create a button component with an attached image

I am currently utilizing React with Typescript. How can I incorporate an image into my button? I've attempted to do so without any errors, but the button appears blank. What's the best way to style my button element using Emotion CSS in this ...