Having numerous calls to isNaN within a JavaScript if-else statement

I've created a JavaScript function that generates div elements and styles them based on user input values. However, I'm facing an issue when trying to display a warning message if the input is not a number. Currently, I'm unable to create the div elements at all; only the warning about the input not being a number pops up.

Here's my code:

function genFigures(){
    var numberFig = numberFigInput.value;
    var widthValue = figWidthInput.value;
    var heightValue = figHeightInput.value;
    var colorValue = figRgbInput.value;
    var leftValue = figPosLeftInput.value;
    var topValue = figPosTopInput.value;

    if (numberFig >= 1001){
        alert("You need to input a value between 1 and 1000!");

    }if (isNaN(numberFigInput) && isNaN(figWidthInput) && isNaN(figWidthInput) && isNaN(figPosLeftInput) && isNaN(figPosTopInput)){
        alert("You have to insert a number!");

    }else{
        for(var amount = 0; amount < numberFig; amount++){
            myFigures.innerHTML += "<div></div>";

            var figStyle = document.getElementsByTagName("div");

            for(var i = 0; i < figStyle.length; i++){
            figStyle[i].style.width = widthValue +"px";
            figStyle[i].style.height = heightValue +"px";
            figStyle[i].style.background = "rgb(" + colorValue + ")";
            figStyle[i].style.left = leftValue +"px";
            figStyle[i].style.top = topValue +"px";

            }

        }
    }
}

Answer №1

Do you remember why you added those extra variables?

This is the correct way to do it:

if (isNaN(numberFig) && isNaN(widthValue) && isNaN(colorValue) && isNaN(leftValue) && isNaN(topValue)){
        alert("Please enter a number!");

Instead of ..., use either colorValue or heightValue. It seems like you repeated figWidthInput twice.

Answer №2

Checking isNaN() is not the most effective method for determining if a user input is a number. The best approach is to utilize parseInt(), such as: parseInt(inputValue, 10).

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

The compare function in bcryptjs will result in a false output if the passwords include numerical

I have successfully used bcryptjs to hash my passwords during user registration. However, I am facing an issue with the bcrypt.compare function when attempting to log in. The function returns a false promise when passwords contain numbers or special charac ...

The HTTP response object in Express does not provide any data in its return

While working on developing a server using express js, I encountered an issue. When I send a get request to my endpoint from another server, the response is received successfully; however, it does not contain the data that was sent by the server after res. ...

Unable to eliminate blue highlighting in Chrome when an element is in focus

After clicking on the search button, there seems to be a persistent blue outline that CSS is not correctly removing despite the settings I've applied. Here is the CSS code I have used: input:focus { -webkit-tap-highlight-color: rgba(0,0,0,0); outl ...

Introducing a variety of sub-menu fonts within an elegantly designed jQuery vertical accordion menu

I am struggling to achieve different font sizes, colors, and weights for top and sub-menu level links in my simple jQuery vertical accordion. Despite changing the CSS, I can't seem to get it right. What am I missing? Is there an easy way to accomplish ...

Send the AJAX form identifier when submitting

There are multiple AJAX forms on the page which contain the same elements. I have a jQuery function that searches for child elements of the form and updates them on success. However, I need to find a way to pass the ID of the form that sent the request to ...

Generating unique ObjectIDs for each object is crucial before saving documents in Mongoose

I need to generate a unique ObjectID for every object within my array. The challenge is that I am fetching products from another server using a .forEach statement and adding them to my array without a Schema that automatically creates an ObjectID.... Prod ...

What is the proper way to mention JavaScript packages when including them as parameters in Angular elements within HTML?

I was looking to enhance the command to be more authoritative. <div (click)="lastCall(999)">click me</div> My attempt to utilize Number.MAX_SAFE_INTEGER resulted in an error from my computer stating that it wasn't recognized. As a result ...

Vue.js component fails to load $refs

One of my Vue.js components features a modal view with various embedded references. <template> <div> <b-modal ref="modalDialog" > <b-row> <!-- document --> <b-col> &l ...

What is the best way to handle a select input that may have varying options in

I'm struggling to figure out how to make each select input independent of each other when rendering them through a map function. How can I correctly implement this, especially considering that the data will be coming from a redux store in the future? ...

What is the best way to position a Radio group next to a TextField in Material UI

I've been through the documentation, but I'm struggling to understand how styling works in Material UI. Currently, I have a radio-group component set up like this: import React from 'react' import Radio from '@material-ui/core/Rad ...

Exploring modifications in axis for Google charts timeline

Can anyone help me figure out how to set my Google Timeline chart to always display 24 hours on the x-axis? Currently, it automatically changes based on the earliest and latest points, but I want it to consistently show all 24 hours. For example: ...

When moving from Babel version 5.8.35 to 6.0.0, be prepared for app.js to throw a SyntaxError and encounter an unexpected token during compilation

Currently, I am in the process of enhancing my ReactJS components using webpack. However, I have encountered a hurdle while trying to transition from babel version 5 to 6. Upon attempting the upgrade, it resulted in a stack trace error within my app.js cl ...

Tips on saving a form submit button data to localStorage

As a newcomer, I am on a quest to make this function properly. My goal is to create a form where the submit button saves data to the localStorage. Here's what I have tried thus far. <script> function storeRecipe() { localStorage.setItem($(" ...

Retrieve data points from ol.layer.Vector using OpenLayers 4

Having recently started using OpenLayers, I find myself in a state of confusion. I'm attempting to retrieve all features from a kml vector layer, but have been unsuccessful thus far. It perplexes me as to what mistake I might be making. Below is the ...

Sending user input from a Laravel modal form to a controller as a parameter

I have a button that triggers a modal form where the user can update their group name. I'm trying to pass the ID into the form using {!! Form::open(['action' => [ 'ContactsController@update', id]]) !!}. I attempted to do this si ...

Messages traced by log4javascript are not being displayed

I am currently utilizing log4javascript version 1.4.3. Everything in my application seems to be functioning correctly with all log levels except for trace. To simplify the troubleshooting process and ensure that the issue does not lie within my applicati ...

Components in React are unable to be accessed

I'm a complete beginner when it comes to React and I'm facing issues with organizing my components into separate files. The error message I encounter is: ERROR in ./src/App.js 5:0-34 Module not found: Error: You attempted to import /components/ ...

Using Javascript to automatically submit a form when the enter key is pressed

Can anyone help me with a password form issue? I want the enter key to trigger the submit button but it's not working for me. I understand that the password can be viewed in the source code, this is just for practice purposes. <!DOCTYPE html> & ...

Unable to remove the most recently added Object at the beginning

I am currently working on a project to create a dynamic to-do list. Each task is represented as an object that generates the necessary HTML code and adds itself to a div container. The variable listItemCode holds all the required HTML code for each list it ...

In JavaScript or jQuery, what is the most optimal method to swap out all instances of a specific string within the body content without altering the rest of the body text?

Is there a way to replace specific occurrences of a string within a web page's body without disrupting other elements such as event listeners? If so, what is the best method to achieve this? For example: Consider the following code snippet: <body ...