JavaScript - Not a Number

I am currently facing an issue while attempting to calculate the Markup of a product. I keep receiving a 'NaN' error in my console, which I understand stands for Not a Number. However, I am struggling to identify and rectify the root cause of this error.

function calculateSuggestedCost() {
    var suggestedCost = 0;
    var idealGP = $('#bc_inventorybundle_dish_ideal_gp').val;
    var cost = $('#bc_inventorybundle_dish_cost').val;

    suggestedCost = parseFloat(cost /(1 - idealGP));


     $('#bc_inventorybundle_dish_suggested_price').val(suggestedCost);   

}

//    =Cost/(1-Margin Percentage)

I've attempted to utilize parseFloat to address this issue, but it seems like my implementation is not quite correct.


Thank you for all the prompt responses. I made some adjustments based on Joe Frambach's suggestion and below is my final corrected code for reference by others encountering a similar problem.

function calculateSuggestedCost() {
    var suggestedCost = 0;
    var idealGP = parseFloat($('#bc_inventorybundle_dish_ideal_gp').val());
    var cost = parseFloat($('#bc_inventorybundle_dish_cost').val());

    suggestedCost = Math.round(cost /(1 - (idealGP/100)));
    $('#bc_inventorybundle_dish_suggested_price').val(suggestedCost);
    calculateActualGP();
}

Answer №1

Remember, in jQuery the val function requires () to be called as it is a function:

var idealGP = $('#bc_inventorybundle_dish_ideal_gp').val();
var cost = $('#bc_inventorybundle_dish_cost').val();

It's always recommended to convert numbers from external sources into actual numbers and validate them immediately rather than during calculation:

var idealGP = parseFloat($('#bc_inventorybundle_dish_ideal_gp').val());
var cost = parseFloat($('#bc_inventorybundle_dish_cost').val());

suggestedCost = cost /(1.0 - idealGP); // This way you can ensure all values are numbers before proceeding with calculations.

Answer №2

When attempting to retrieve a value from an input field or element, make sure to use .val() instead of just val.

var idealGP = $('#bc_inventorybundle_dish_ideal_gp').val();

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

What is the best way to upload a canvas image from a GUI to the back-end using an AJAX call and setting the content-type as "image/jpeg"?

What is the best method for saving a canvas image from GUI to back-end using an AJAX call that accepts content type "image/jpeg" and avoids the error "jquery.js: 8453 Uncaught TypeError: Illegal invocation?" HTML <canvas id="myImage"></canvas> ...

Import a picture file into Photoshop and position it at a designated location

I need assistance with developing a function that can load an image and position it at specific x, y coordinates in Photoshop. Below is the code I have so far: var docRef = app.activeDocument; function MoveLayerTo(fLayer, fX, fY) { var Position = fLaye ...

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

Is it possible to remove the address bar from appearing on a browser when a page loads?

I am in the process of developing a customer wifi landing page, and although we have made progress with ensuring it is the first page that loads, I want to take it a step further. My goal is to require customers to agree to our usage policy before gaining ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

Modifying the data of a particular object in my rtk asynchronous thunk

I recently started using rtk and immer. I encountered an issue when trying to update my state with redux. For example, when a user logs in, I store their data in redux with the following structure: data = { "user_profile" : { "name&q ...

Steps for clearing a set of checkboxes when a different checkbox is selected

While working on a website I'm developing, I encountered an issue with the search function I created. The search function includes a list of categories that users can select or deselect to filter items. This feature is very similar to how Coursera has ...

The Sequelize error message states: TypeError: an array or iterable object was expected, but instead [object Null] was received

I am encountering an issue with the findOne method from sequelize in my model. The error message I am getting states that the table referenced by the model is empty. How can I resolve this? Unhandled rejection TypeError: expecting an array or an iterable ...

jqgrid now features inline editing, which allows for the posting of only the data that

My jqGrid includes editable columns, and I am looking for a way to only post the data of columns where changes have been made. Here is an example of my colModel: colModel: [{ name: 'I_PK', index: 'u.I_PK ...

Using AngularJS to encapsulate an externally loaded asynchronous library as a service

Is there a way to wrap a 3rd party library that loads asynchronously into an Angular service? What is the best practice for incorporating such libraries as services in Angular? Currently, I am approaching it like this: angular.module('myAPIServices ...

The React useEffect hook runs whenever there is a change in the state

Within my React component, I have the following code snippet (excluding the return statement for relevance): const App = () => { let webSocket = new WebSocket(WS_URL); const [image, setImage] = useState({}); const [bannerName, setBannerName] = use ...

How can I pass the data-attribute ID from JavaScript to PHP on the same index page using ajax?

I am struggling with the title for this section. Please feel free to modify it as needed. Introduction: I have been working on setting up a datatables.net library server-side table using JSON and PHP. Most of the work is done, but I am facing challenges w ...

Does LABJS include a feature for executing a callback function in the event of a timeout during loading?

When using LabJS to asynchronously load scripts with a chain of dependencies, if one of the scripts breaks (due to download failure or connection timeout), it seems that the remaining scripts in the chain will not be executed. Is there a way to define a ...

Utilize the grouping functionality provided by the Lodash module

I successfully utilized the lodash module to group my data, demonstrated in the code snippet below: export class DtoTransactionCategory { categoryName: String; totalPrice: number; } Using groupBy function: import { groupBy} from 'lodash&apo ...

Tips for dynamically passing a URL to a function using the onload event

I require assistance with passing a dynamic URL to a function. code onload="getImage('+ val.logo +');" onclick="loadPageMerchantInfo('+ val.merchant_id +'); The value of val.logo contains a URL such as: https://www.example.com/upload ...

Implementing Text Box Control Validation within a Gridview using UpdatePanel in c# ASP.Net

In my gridview, one of the columns contains a Text Box Control. I am looking to validate the text entered by users as alphanumeric characters and spaces only. Allowed characters are: a-z, A-Z, 0-9, and space. I want to perform this validation using Java ...

Experiencing difficulties with mocha and expect while using Node.js for error handling

I'm in the process of developing a straightforward login module for Node. I've decided to take a Test-Driven Development (TDD) approach, but since I'm new to it, any suggestions or recommended resources would be greatly appreciated. My issu ...

"Trouble arises when dealing with nested object arrays in Formik and handling changes in a child

I am struggling with passing a value to handleChange in formik validation. To address this issue, I created a component whose quantity is dynamically added based on the number of numChild. My goal is to allow users to click an icon and add any number of sk ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...