Javascript - formatting numbers with decimals

This question is not related to math or operators, but rather a formatting or masking issue.

I am working on creating an order form that uses Javascript to tally and display the quantity and cost of each column in separate fields. I am trying to format the column cost to display with two decimal places, but the .toFixed(2) method does not seem to be working as expected (possibly due to it being a string), and I suspect it may be because the quantity and cost fields are set to readonly.

Any help would be greatly appreciated as I am currently stuck.

    //example of tallying one column

    <input type="number" min="0" value="0" name="proA#x#" class="input-mini proA qty1 coffee total">

    $(document).on("change", ".qty1", function() {
        var sum = 0;
        $(".qty1").each(function(){
            sum += +$(this).val();
        });
        $(".total1").val(sum);
        $(".cost1").val(sum*9.00);
    });


    //item tally

    <input type="number" id="D1" name="D1" class="input-mini uneditable-input total1" placeholder="0" readonly>


   //item cost

   <input type="number" id="" name="" class="input-mini uneditable-input cost1" placeholder="x 9.00" readonly >

Thank you for any assistance you can provide!

Answer №1

This is how I would approach the problem:

let total = 0.00;
$(".quantity").each(function(){
     total += parseFloat($(this).val());
});

$(".totalCost").val(total.toFixed(2));

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

Incapable of modifying the text within a div container

I am currently working on a script that translates a Russian forum word by word using TreeWalker. However, there is a specific type of div element that I have been unable to change the text for. That leads to my question: How can I go about changing it? Un ...

Avoiding mocking a specific module with jest forever

Our codebase heavily relies on underscore in various parts, and I prefer to avoid mocking it. I'm aware that I can use jest.unmock('underscore'); in each test that utilizes underscore. Is there a method to unmock underscore across all tests ...

What is the best way to incorporate an apostrophe into a string so that it can be displayed in a tooltip using jQuery

There is a text or string stored inside the 'data' variable, containing some texts with apostrophes. The issue I'm facing is that the tool tip is not displaying the text after the apostrophe symbol. How can I include all texts, including apo ...

What is the best way to access the child component in React?

const navArr = [ { path: "/introduction", title: "회사소개", subTitle: [{ title: "summary" }, { title: "vision" }], }, ] {navArr.map((obj) => { return ( <NavItem> ...

Accessing the name attribute of the TextField component, displayed as a Select Box in Material-UI, by utilizing the event object received from the onFocus prop

Utilizing the "@material-ui/core": "4.11.2" library along with "react": "16.8.6", I've encountered an issue with the TextField component where the select prop is set to true. Specifically, I am unable to access ...

Pressing the icon will trigger a top-sliding dropdown mobile menu to appear

How can I ensure my mobile dropdown menu slides in from the top when the user clicks the "header-downbar-menu" icon and slides out to the top when clicked again? Currently, the button only shows the menu but I am struggling with writing the JavaScript for ...

What causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

What could be the reason behind receiving an "undefined" message when attempting to access db.collection in the provided code snippet?

var express = require('express'); var GoogleUrl = require('google-url'); var favicon = require('serve-favicon'); var mongo = require('mongodb').MongoClient; var app = express(); var db; var googleUrl = new GoogleUrl( ...

Exploring the functionality of multiple index pages in angularjs

I am trying to access the localhost:3000/admin which is located in my views. The index.html and admin.html are two separate base files, one for users and the other for the admin dashboard respectively. Here is a snippet from my app.routes.js file: angul ...

Just starting out with Angular - facing issues with setting up in eclipse

I'm attempting to create a test Angular project in Eclipse by copying the three files from the Angular website https://docs.angularjs.org/api/ng/directive/ngController into my Eclipse project. I initially created it as a static web project and then co ...

Extracting web search result URLs using Puppeteer

I'm currently facing an issue with the code I've written for web scraping Google. Despite passing in a specific request, it is not returning the list of links as expected. I am unsure about what might be causing this problem. Could someone kindly ...

Problem encountered when trying to use a single button for both opening and closing functionality in JQuery

Hello everyone, I'm currently working on creating a button that toggles between opening and closing. When clicked the first time, it should open, and when clicked the second time, it should close and reset. Here is the code I've written so far. ...

Learn how to properly display the state array within a React component. Even though the array is present in the state, you may encounter issues where it

I am facing an issue while trying to display data from firestore in my React component. I have updated the global state array with the firestore data and it is being updated, but when I try to render that array, it shows as undefined. Initially, I attempt ...

Incorrect ng-pattern does not enable the tooltip to be activated

I have implemented the ng-pattern="/^[0-9]{9}$/" in an input field that appears as follows: <input type="text" id="company_taxId" ng-model="company.taxId" required="required" class="input ng-scope ng-valid-maxlength ng-valid-mi ...

What is the best way to conceal a specific class of DIV within a container, and how can I also hide another DIV within the same container by

I have a DIV class containing around 10 elements within a container. I am looking to implement a feature where these elements are hidden and shown one by one every 15 seconds using jQuery with a smooth fadeOut() effect. Your assistance in achieving this wo ...

Can we access local storage within the middleware of an SSR Nuxt application?

My Nuxt app includes this middleware function: middleware(context) { const token = context.route.query.token; if (!token) { const result = await context.$api.campaignNewShare.createNewShare(); context.redirect({'name': &a ...

Tips for transferring information from one php page to another php page via ajax

I am attempting to retrieve data from one PHP page and transfer it to another page through the use of Ajax. JavaScript : $.ajax({ url: "action.php", success: function(data){ $.ajax({ url: "data.php?id=data" ...

Is there a way to prevent my token from being exposed when making an AJAX call?

When working on my HTML file, I encountered an issue with a Python Django URL integration where I need to pass a token to retrieve certain information. However, the problem is that my token is exposed when inspecting the page source in the HTML document. ...

What can be done to ensure that the a href tag is functioning as clickable?

Having an issue with my HTML and CSS code for a notification dropdown box. I am unable to click the tag, even after attempting to use JavaScript. Can't seem to figure out what's causing this problem. Any advice on how to make the tag clickable? ...

Retrieve information from internet sources

I'm attempting to extract the initial paragraph from Wikipedia by utilizing only JavaScript. Essentially, my goal is to: document.getElementsByTagName("P")[0] However, this content is not present on my own website; instead, I aim to retrieve a speci ...