Issues with the parseInt() Function

I'm having trouble figuring out why parseInt() isn't working correctly in my code, especially when passing numbers through to my function parameters. It keeps returning NaN in both my array and the function's return value.

What I'm attempting to do is to display the index percentage of two values entered into input fields in the HTML and store the value in an array. I'm using a function for this because I need to perform over twenty outlet calculations. I'm also finding it challenging to refactor this code as I'm not very experienced with JS. Any assistance would be greatly appreciated.
Here is my HTML.

function outletIndex(actual, design) {
    
    let result1 = actual / design * 100;
    var indexArray = [];
    indexArray.push(result1);
    console.log(indexArray, result1);
    if (!isNaN(result1)) {
    document.getElementById("percentage").textContent = `${result1.toFixed(1)}%`;
    
  }
}
  const x = parseInt(document.getElementById("outlet_actual_1" ).valueAsNumber);
  const y = parseInt(document.getElementById("outlet_design_1").valueAsNumber);
  
  const outlet1Index = outletIndex(x, y);
 <table>
      <tr>
        <div class="form-group row 1" id="outlets1">
          <td><label
            >Outlet Design</label>
            <input
              name = "outlet 1 design"
              class="form-control design_1"
              id="outlet_design_1"
              type="number"
              placeholder="Outlet 1 Design"
              
            />
          </td>
          <td><label
            >Outlet Actual</label>
            <input
            name="outlet 1 actual"
              class="form-control actual_1"
              id="outlet_actual_1"
              type="number"
              placeholder="Outlet 1 Actual"
              onblur="outletIndex();"
            />
          </td>
          <td><label
            >Outlet Balance</label>
            <input
              name="outlet_balance"
              class="form-control"
              input value=""
              id="outlet_balance_1"
              type="text" 
              placeholder="Outlet 1 Balance"        
            />
          </td><td>
            <div class="proportion" id="percentage">

            </div>
          </td>
        </div>
      </tr>

Answer №1

The primary issue at hand arises from the code that attempts to access the variables x and y before they have been assigned any values.

Another challenge arises when utilizing the blur event on the control with the ID outlet_actual_1 without passing the required arguments actual and design to the method.

Furthermore, when using valueAsNumber, there is no need to use parseInt. However, if you choose to use it, ensure that you specify the radix when reading the value like so:

parseInt(document.getElementById("outlet_actual_1").value, 10)

A straightforward solution would be to relocate the code that accesses x and

y</code within the method and eliminate the arguments. Yet, it is likely that additional modifications are necessary; perhaps you intend to recalculate whenever either field is altered, in which case, that can be included as well:</p>
<p><div>
<div>
<pre class="lang-js"><code>function outletIndex() {
    const actual = document.getElementById("outlet_actual_1").valueAsNumber || 0;
    const design = document.getElementById("outlet_design_1").valueAsNumber || 0;
    let result1 = actual / design * 100;
    var indexArray = [];
    indexArray.push(result1);
    console.log(indexArray, result1);
    if (!isNaN(result1)) {
    document.getElementById("percentage").textContent = `${result1.toFixed(1)}%`;
    
  }
}
<table>
      <tr>
        <div class="form-group row 1" id="outlets1">
          <td><label
            >Outlet Design</label>
            <input
              name = "outlet 1 design"
              class="form-control design_1"
              id="outlet_design_1"
              type="number"
              placeholder="Outlet 1 Design"
              onblur="outletIndex();"
            />
          </td>
          <td><label
            >Outlet Actual</label>
            <input
            name="outlet 1 actual"
              class="form-control actual_1"
              id="outlet_actual_1"
              type="number"
              placeholder="Outlet 1 Actual"
              onblur="outletIndex();"
            />
          </td>
          <td><label
            >Outlet Balance</label>
            <input
              name="outlet_balance"
              class="form-control"
              input value=""
              id="outlet_balance_1"
              type="text" 
              placeholder="Outlet 1 Balance"        
            />
          </td><td>
            <div class="proportion" id="percentage">

            </div>
          </td>
        </div>
      </tr>

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

Choice of product variations as a package

I am currently working on a project and here is the data structure I have set up for options and combinations: https://i.sstatic.net/K2utM.gif Options: "options": [ { "id": "96ce60e9-b09b-4cf6-aeca-83f75af9ef4b", "posit ...

What steps should I take to address the issues with my quiz project?

I've been working on a new project that involves creating a quiz game. I came across some code online and decided to customize it for my needs. However, I'm encountering some issues with the functionality of the game. Right now, the questions ar ...

Tracking progress in a Rails job using Coffeescript

Recently, I came across a helpful gem called this gem, which allows for the seamless integration of bootstrap progress bars and the delayed job gem. The example provided by the creator uses .haml files, but since my project utilizes erb and coffeescript, I ...

Checking the submission text field with Javascript is being confirmed

It seems I've made a small mistake somewhere, and I would appreciate it if someone could help me find it. I'm attempting to validate a postcode in a form field once it's been entered. I've tried similar code in PHP, and it works fine, b ...

How do I use props to enable and conceal elements like lists, buttons, and images?

Check out this unique component: <ReusedHeader H1headerGray="text here... " H2headerRed="text2 here ! " pheader="p1" getStarted="button text1" hrefab="button url 1" whatWeDo="button text ...

Utilize the power of Wikitude within an Angular 2 application

I am currently working on integrating Wikitude Architect View in Angular 2 by referring to the code at this link. My goal is to implement this code in an Angular 2 compatible way. import * as app from 'application'; import * as platform from & ...

What could be the reason for the container div's height not being properly refreshed?

When adding elements to a container div with an initial height of 'auto', I assumed that the height would adjust based on the children elements added. However, this is not happening. Can anyone assist me in ensuring that the container div's ...

Download a file on button click using JavaScript with data extracted from the DOM

I am looking to create a download feature where a user can click a button on the webpage, triggering a JavaScript method to capture the contents of a DOM element and prompt the user for a download. After successfully capturing the DOM element in a JavaScr ...

Unique Symbols and Characters in JavaScript

My JavaScript code looks like this: confirm("You are selecting to start an Associate who is Pending Red (P RD) status. Is this your intent?") I am encountering a strange issue where I get an alert with special characters, even though my code does not con ...

dimming of dojo dijit.Dialog

I've been encountering issues with "undimming" a Dojo Dijit dialog. Even though I am using the appropriate calls, there are instances where parts of the page remain dimmed. I can still scroll through the windows and access the undimmed sections. Is th ...

Trouble getting a sticky element to align with a two-column grid within a parent container

I'm looking to keep one column sticky in a two-column grid setup. My goal is to create a vertical navigation bar that's specific to a particular div within a single-page site, with a fixed horizontal navbar across the entire page. However, I&apos ...

Separate and add on the change validity status of an AngularJS form

If you want to test it out, check this jsFiddle link: HERE (it's recommended to view on a new jsFiddle, refer to the EDIT section of this post) I've noticed what seems like a bug in AngularJS or at least an unexpected behavior. When I detach a f ...

What is the best way to empty an input field after adding an item to an array?

In my Angular 2 example, I have created a simple functionality where users can add items to an array. When the user types something and clicks the button, the input is added to the array and displayed in a list. I am currently encountering two issues: 1 ...

employing varying array sizes in a function

I'm currently working on a function that integrates a set of arguments from the rows within a 2d array with all elements contained in a longer 1d array: x = np.linspace(-10,10,100) abc = np.array([[1,2,1], [1,3,5], [12.5,-6.4,-1.25], ...

Getting rid of mysterious Google Analytics script from WordPress

My client has requested that I incorporate Google Analytics into her website. After accessing her Google account, I attempted to paste the tracking code into the appropriate section of the Wordpress plugin. To my surprise, the code did not work as expect ...

Enhancing an existing node by adding a new node with jQuery functionalities at the same time

Is it possible to append a node to a parent node while also manipulating the node being added? I initially believed this could be done in one step: //I though this was possible: $('#master').after('<div id="test" style="border:solid 1px ...

exploring numerous boxes in an engaging and educational tutorial

Explaining this in the title was a bit tricky, but what I want to create is an interactive tutorial. In this tutorial, the user will click on an area or product they want to clean or use for cleaning. After clicking, another box with relevant information w ...

Currently, I am attempting to retrieve text input through the use of AngularJS

Having trouble retrieving text input values using Angular JS? The console keeps showing undefined. <div ng-controller="favouritesController" class="col-xs-12 favList"> <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-1 ...

Exploring the use of Vue 3 Composition API, managing Props, and implementing v-if rendering even with a

I'm encountering an issue that I need some help with. In my setup, I have a child component that passes an "active" prop which can be set to either true or false. The intention is for a certain part of the component to show if it's passed as true ...

Combine and emphasize several gridview rows into a single highlighted unit

Imagine you have a gridview that looks like this: FAMILY GROUP COLOR =============================================== | | Poodle | Blue ROW1 | DOG | German Shepherd | Red | | Pitbul ...