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

Getting hands-on with Express.js and gaining a foundational understanding of Angular

Thank you for taking the time to read my inquiry. As a developer experienced in PHP, particularly with Laravel, and possessing basic knowledge of AngularJS concepts such as routing, directives, and resource, I have been utilizing Laravel on the backend an ...

Looking to optimize this code? I have three specific tags that require reselection within a given list

for (var i=0; i<vm.tags.length; i++) { if (selectedTags[0]) { if (vm.tags[i].term_id === selectedTags[0].term_id) { vm.tags[i].border1 = true; } } if (selectedTags[1]) { if (vm.tags[i].term_id === selecte ...

Change the size of Jive Addon Tile in a vertical orientation

Seeking assistance with resizing the tile container in an angular application embedded within a Jive tile when the view changes. Any advice on how to tackle this issue? This particular tile is deployed to a Jive Cloud instance using a Jive add-on. ...

The synchronization event and its attributes

Greetings esteemed individuals of Stackoverflow, I have implemented a persistent SharedObject for Adobe Media Server in order to efficiently store and share data in real-time among multiple clients. My focus is on utilizing the SyncEvent to trigger notif ...

Merging scripts to minimize HTTP requests - The Takeover of the Body Swappers

For my website design, I've implemented the Invasion Of The Body Switchers script from brothercake.com. This script involves loading three separate js files in the header. I'm looking to optimize my site by reducing the number of HTTP requests a ...

Troubleshooting Problems with Adjusting Left Margin Using JQuery

function adjust_width() { $('#cont').toggle(function(){ $('#cont').animate({marginLeft:'0%'}); },function(){ $('#cont').animate({marginLeft:'18.4%'}); }); } The code above is in ...

require an array that contains an embedded object

When making a post request, I need to include an array with an object inside. I have observed that adding new properties inside an object works fine. However, when attempting to add properties while the object is inside an array, it does ...

Implementing async and await after making a fetch request

I am in the process of updating my code from using callbacks to utilize async and await. However, I am a bit confused on how to properly implement it within my current setup. The current setup involves: Clicking a button that triggers the clicker functi ...

Looking to design an interactive grid for generating dynamic thumbnails

I am a beginner in the field of web development and I have a desire to create a website for showcasing my portfolio. This website should feature project thumbnails along with brief descriptions, all of which should be displayed dynamically. Although I poss ...

Does React reassign keys once the underlying data structure has been modified?

Exploring the ins and outs of React, particularly diving into how the Reconciliation process functions. In my JSX code, I have a map function that looks like this: render: function () { var currentIssues = this.state.issues.map(function(issue, ...

Dealing with onChange value in a date in reactjs is a common challenge that developers

I'm currently working on a basic date input component in React, but I've run into an issue when trying to change the value. Every time I update it, it always displays "1970-01-01". If anyone has any suggestions on how to fix this problem, I woul ...

Efficiently converting arrays to strings in JavaScript using mapping techniques

My goal is to retrieve data through AJAX without formatting it as JSON, so I took the initiative to encode it myself. The data I am working with consists of client records: where the pound sign (#) separates the client records, the pipe sign (|) separates ...

Is there a way to modify the appearance of blocks in Scratch/Blockly?

I am currently working on customizing the appearance of the blocks in Scratch by looking into adjusting the GitHub repository of scratch-blocks (https://github.com/LLK/scratch-blocks). There is a chance that I might need to modify the GitHub repository of ...

Arrange a collection of objects by two criteria: the end time, followed by the status in accordance with the specified array order if the end times are equal

Is this the best method to arrange data by using infinity? I gave it a try but it doesn't quite meet my requirements. data = [{ "status": "Accepted", "endTime": "" }, { "status": "New", ...

"Integrate a URL segment into the primary URL with the help of AngularJS or JavaScript

One interesting case involves a URL path that is structured in the following way. http://localhost:12534/urlpart1/urlpart2?querystring=140 The challenge here is to replace "urlpart2" with "urlpart3" using either javascript or AngularJS. One approach is t ...

Scaling a mesh and BufferGeometry vertices using THREE.OBJLoader

Utilizing the THREE.OBJLoader, I successfully loaded a 3D model into my scene. Subsequently, I have the necessity to scale it by 10 and then extract its vertices position. I am aware that the THREE.OBJLoader provides a BufferGeometry, allowing me to acce ...

Create a set of n randomly generated points, represented as latitude and longitude pairs, originating from the central point of a polygon while remaining within the boundaries

I am currently trying to plot data within a polygon (District), but unfortunately, I do not have specific coordinates for each of the data sources in that district. My goal is to accurately display all the results from a district within its boundaries, wh ...

Simply modifying a custom attribute source using jQuery does not result in it being refreshed

Introduction: Utilizing jQuery.elevateZoom-3.0.8 to display zoomed-in images. The SRC attribute contains the path to the smaller/normal image The DATA-ZOOM-IMAGE attribute holds the path to the larger image used for zooming. Here is the HTML Code: ...

How to insert text into a text input using onKeyPress in react.js

I am looking to simulate a typing effect where the phrase 'Surveillance Capitalism' is inputted letter by letter into a text input field as a user types. However, I encounter an issue when trying to add each individual letter into the input; I re ...

Javascript Rest for y moments

My website's JavaScript function uses AJAX to retrieve account information and open a modal for viewing and editing. Sometimes, the details don't update quickly enough in the database before the function collects them again, leading to discrepanc ...