What steps can I take in JavaScript to assign a value of 0 to values[1] in order to prevent receiving NaN as the output

I'm currently working on a program that calculates the sum of 6 input values, but I've encountered an issue where if a value is missing (for example, only providing 5 values), the result becomes NaN. I attempted to address this by assigning empty values a default of 0 using a for loop and an if statement, however, it doesn't seem to be working as expected. Could someone please assist me with this?

Here's the code snippet:

document.getElementById("b").onclick = function() {

  var values = new Array();
  values[0] = document.getElementById("x").value;
  values[1] = document.getElementById("y").value;
  values[2] = document.getElementById("z").value;
  values[3] = document.getElementById("a").value;
  values[4] = document.getElementById("g").value;
  values[5] = document.getElementById("c").value;

  for (i = 0; i < values.length; i++) {
    if (isNaN(values[i])) {
      values[i] = 0;
    }
  }

  var sum = parseFloat(values[0]) + parseFloat(values[1]) + parseFloat(values[2]) + parseFloat(values[3]) + parseFloat(values[4]) + parseFloat(values[5]);

  document.getElementById("result").innerHTML = "The total sum is " + sum + ".";
}
<form>
  <input type="number" placeholder="Value 1" id="x" required>

  <input type="number" placeholder="Value 2" id="y" required>

  <input type="number" placeholder="Value 3 (optional)" id="z">

  <input type="number" placeholder="Value 4 (optional)" id="a">

  <input type="number" placeholder="Value 5 (optional)" id="g">

  <input type="number" placeholder="Value 6 (optional)" id="c">

  <input type="button" class="btn btn-primary" id="b" value="Apply" />
</form>

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

Edit: This is not a duplicate because the question that I wrote here (Why can't I do addition between 4 variables in JavaScript but I can do it with 3 variables?) is about the addition, and this one is about handling isNaN values.

Answer №1

When an empty string is checked with the isNaN function, it will return false because an empty string is considered as zero (a number). To handle this properly, make sure to use parseFloat on the value before checking for NaN. Using parseFloat will correctly return NaN for empty strings. Another approach would be to directly check if the string is empty.

For example: if (isNaN(parseFloat(values[i])) or (values[i].length === 0)

For a simpler way of achieving the same result, you can do something like this: (parseFloat(a) || 0). This means that if a is NaN, it will be replaced with 0.

Answer №2

Ensure that each input has a unique class name assigned to it. Utilize document.querySelectorAll() to gather all the inputs. Next, loop through the array of inputs. Convert each value into a string using the + operator and provide a default value of 0 if the result is NaN. Store the cumulative sum in a variable called sum.

document.getElementById("b").onclick = function() {
  var inputs = document.querySelectorAll('.number'); // select all elements with the .number class
  var sum = 0; // initialize sum

  for (i = 0; i < inputs.length; i++) {
    sum += +inputs[i].value || 0; // convert each value to a number, substitute 0 if isNaN
  }

  document.getElementById("risultato").innerHTML = "The total mass of the product is " + sum + ".";
}
<form>
  <input type="number" placeholder="Value 1" class="number" required>

  <input type="number" placeholder="Value 2" class="number" required>

  <input type="number" placeholder="Value 3 (if applicable)" class="number">

  <input type="number" placeholder="Value 4 (if applicable)" class="number">

  <input type="number" placeholder="Value 5 (if applicable)" class="number"">

  <input type="number" placeholder="Value 6 (if applicable)" class="number">

  <input type="button" class="btn btn-primary" id="b" value="Apply" />
</form>

<div id="risultato" class="desc"></div>

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

Deactivating the ajax function is one of the key features of the Framework

I recently attempted to transition my app from plain HTML to framework 7, and while most things were running smoothly, I ran into a roadblock when it came to ajax requests. They simply wouldn't execute, resulting in an error message. Uncaught TypeErro ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

Text will split into two at a later time

I am using the material-ui library. Curious about adding a text followed by a line divider. Here's how I attempted it: <Grid> <Typography variant="h6" color="primary"> {'text'} </Typograph ...

Encountering a 500 internal server error while accessing the web server

Anyone out there able to assist? My web service seems to be throwing an error. Receiving a 500 Internal Server Error and 304 Not Modified message The requested XML data is not displaying the body content as expected. var soapMessage ='<soap:E ...

Error message: Trying to call the prepare() function on a null variable within the CRUD system

I have implemented a CRUD system on my website. The main page (avisos.php) displays a table with all the existing records. When a user clicks on the "ADD NEW RECORD" button, the following script is triggered: $("#btn-add").click(function(){ $(".co ...

"Experience the power of Angular.js through seamless animations created by blending the capabilities

I want to smoothly fade out the old view and fade in the new view. The challenge is that the new content must be positioned absolutely until the old one fades out. I also want to set a specific top position and height for the new content, but when I try to ...

What is the most secure approach for defining the file path of an HTML file within an express.js application?

In my directory setup, I have the index.js file located at: path/to/home-page/src/routes This is also where you can find the __dirname. The html file resides at: path/to/home-page/public/bootstrap/Homepage/page.html To serve the html document by relati ...

What are the steps to executing commands with child processes in Node.js?

I have successfully established communication between the client and server using socket.io. I am now utilizing WebSockets to send commands from the client to the server, and I would like to execute these received commands on the server. Here is my approa ...

Node.js route leads to a 404 error page due to a simple configuration

Trying to set up two separate routes using NodeJS with the express framework and Angular on the client side. The index page successfully renders at localhost:3000/. However, when attempting to render the login page by visiting localhost:3000/login, a GET / ...

Encountering a fatal error in the Next.js application: "Mark-compacts near heap limit allocation failed issue is hindering the smooth

When I'm working in Next.js, I often encounter the issue of not being able to run my project after work. https://i.stack.imgur.com/IA5w3.png ...

encountering the issue of not being able to assign a parameter of type 'string | undefined' to a parameter of type

Seeking help with the following issue: "Argument of type 'string | undefined' is not assignable to parameter of type" I am unsure how to resolve this error. Here is the section of code where it occurs: export interface IDropDown { l ...

What could be the reason for getting undefined when printing console.log(fibonacci(3))?

let array = [0, 1, 1]; const fibonacciSequence = (number) => { if (number < 2) { return array[number]; } else if (number == 2) { console.log(array.length-1); console.log((array[array.length-1])); // return (ar ...

How to Show a GIF in ASP.NET Core 3.0 When OnPost() is Invoked

I'm struggling to incorporate a GIF into my website, and after researching different sources, I've discovered that I need to utilize some Ajax and Javascript. However, I lack experience with both of these technologies. Is there anyone who could p ...

Updating attribute values in a dynamic JSON file with Node.js: A step-by-step guide

My task involves checking if the key in input.json file matches any key in the server.json file, and then updating the value in the server.json file. The challenge lies in the fact that the server.json file is dynamic with an unpredictable structure contai ...

What is the best way to update the array in this situation?

I have a SQL query that looks like this: SELECT test_user_user_id FROM OCN.tests_users WHERE test_user_test_id = 99 $this->mDb->Query( $sql ); $students_data = $this->mDb->FetchArray(); The array I am receiving is as follows: Array ( [0] ...

Can you explain the significance of "@c.us" in the context of whatsapp-web.js?

Are there any references or resources available for using "@c.us" that I can consult? Here is an example: client.on('ready', () => { console.log('Client is ready!'); // Your message. const text = "Hey John"; // Obt ...

Utilizing X-editable in an ASP MVC View: navigating the form POST action to the controller

I have been utilizing the X-Editable Plugin to collect user input and perform server submissions. However, I am encountering an error during submission. What adjustments should I make in order to ensure that the x-editable data functions properly with the ...

Breaking down a lengthy series of items into several smaller lists

I have created a <ul> using the code below: function ListItem(props) { return <li>{props.value}</li>; } function ListLinks() { const listItems = footerLinks.map(section => { return section.data.map(({id, name, to}) => { ...

Do you have an index.d.ts file available for canonical-json?

I am currently working on creating an index.d.ts file specifically for canonical-json. Below is my attempted code: declare module 'canonical-json' { export function stringify(s: any): string; } I have also experimented with the following sn ...

Tips for securely implementing JSON web tokens when integrating an external application with the WordPress REST API

I have a query regarding JWT. Let's consider this situation. A -> wordpress site with wp rest api enabled; B -> External application (for example, a simple javascript/jQuery app) Suppose I want to make a post request or create a new post on the wor ...