Determine the sum of all the values entered into the text fields

On my ASP.Net page, there is a screen where users can select between 1 and 5 text boxes to input an amount. Depending on certain criteria, a specific number of these edit boxes are displayed - no hiding involved. So if I choose to display 3 boxes, only 3 will appear on the screen.

As the user inputs an amount, a 'Total' edit box dynamically updates to show the sum of all values entered in the text boxes. This is achieved using the following JavaScript code triggered by the onkeyup event:

onkeyup="calculateTotal()"

The calculation is carried out by this function:

function calculateTotal() {
        var amt0 = $('.txtAmount0').val();
        var amt1 = $('.txtAmount1').val();
        var amt2 = $('.txtAmount2').val();
        var amt3 = $('.txtAmount3').val();
        var amt4 = $('.txtAmount4').val();

        var amt = Number(amt0);
        if (!isNaN(amt1))
            amt += Number(amt1);

        if (!isNaN(amt2))
            amt += Number(amt2);

        if (!isNaN(amt3))
            amt += Number(amt3);

        if (!isNaN(amt4))
            amt += Number(amt4);

        $('.txtTotalAmount').text('$' + amt);
    }

However, there seems to be a precision issue in the calculation and a need to update the code if more boxes are added. Is there a cleaner, more efficient solution for this functionality?

Answer №1

Here's a way you can achieve this:

  let total = 0;
  $("input[class*='txtAmount']").each(function() {
           if ($.isNumeric($(this).val()) ) {
        total += Number($(this).val());
        }
    });

   $('.txtTotalAmount').text('$' + 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

ReactJS instance.render function error: How to solve it?

I encountered a strange error message while working with reactjs, which states that instance.render is not a function in reactjs. Despite my efforts, I have been unable to identify the source of this error. Below are the contents of index.js and search_bar ...

Adjusting the size of tables in raw JavaScript without altering their positioning

I am attempting to adjust the size of a th element without impacting the position of the next th in the row. Specifically, I want the width of the th to influence the width of the next th accordingly, rather than pushing it to the left. Below is the code ...

What is the best way to integrate AJAX with draggable columns in a Laravel application?

I have successfully integrated draggable functionality for table columns using jQuery Sortable within my Laravel application. I am now facing the challenge of updating the database with the data from these columns through AJAX. Despite researching online ...

Navbar collapse not functioning properly on HTML, CSS, and JavaScript

I have developed a CSS code snippet: .nav{ right: 0px; left: 0px; margin-top: 0px; margin-bottom:20px; height: 35px; text-align: center; background-color: red; z-index: 1; } .sticky { background: #000; text-align: center; ...

Reorganize a list based on another list without generating a new list

Among the elements in my HTML list, there are items with text, input fields, and tables. I also have a specific order list like [3,1,2,0]. Is it feasible to rearrange the items in the HTML list on the page based on this order list without generating a new ...

Navigating Date Conversion within Component in Angular 2 Application

Searching for a way to update the display of certain dates in my Angular 2 application, I encountered a roadblock. Using the date pipe in conjunction with string interpolation wasn't viable due to the structure of my template code: <input class="a ...

Tips for shifting a stuck div 200px upward once the bottom of the page is reached while scrolling:

I've set up a page layout with two columns, one fixed and the other scrollable. The left column is fixed (containing Google ads) and stays in place as I scroll down the page. The right column displays posts and scrolls along with the rest of the con ...

Using ASP.NET MVC to efficiently save nested collection data

Just dipping my toes into ASP.Net MVC, so please be patient with me. :) I've got a view with nested collections that can be updated by the user. Successfully retrieving updated model data from an AJAX call to the controller. Now I have a model with ...

Using JavaScript in Selenium, you can check a checkbox and verify whether it is checked

How can I select a checkbox and determine if it is checked using JavaScript, Selenium, and Node.js? I have attempted to use the .click method on the element and also tried native JavaScript code, but unfortunately it has not worked for me. driver.findElem ...

employing ajax for handling a form

Currently, I am facing an issue with updating a user's email on a page. The div refreshes upon submission as intended, but the database is not being updated, and I can't figure out why. My layout consists of a single page where clicking a menu l ...

NextJS Input Field causing a strange "Hydration Error indicating server HTML should not contain a <div> within a <form>", perplexingly occurring only in Chrome and exclusively on my personal computer

Looking for some assistance with a website I'm working on using NextJS and TailwindCSS. There seems to be a pesky little issue in my code that's causing some trouble. Below is the code snippet for the MainContent section of the page: "use c ...

What could be the reason the forEachRow function is not impacting the second or subsequent pages within the dhtmlx grid?

I'm trying to format the grid rows as they load. My goal is to have the row appear in red with some conditions. It works correctly for the first page, but not for subsequent pages of the grid. Below is my detailed code. If anyone knows why this is hap ...

When submitting a form in HTML, ensure that the input checkbox returns 'On' instead of 'True'

My MVC3 app is using Project Awesome from http://awesome.codeplex.com/, but I'm encountering a strange issue with checkboxes. Inside a Modal popup, I have the following simple Html code: <input type="checkbox" class="check-box" name="IsDeleted"> ...

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

What steps can be taken to ensure that an ObjectID does not transition into a primitive form

Is there a way to avoid an ObjectID from being converted into a primitive data type when transferring in and out of Redis? Would converting it to a JSON string be a possible solution? Thanks! ...

AngularJS - Swipe to update

I've been trying to use the pull to refresh plugin for Angular JS, but unfortunately it's not working for me. Even though I can see the text, when I try to pull nothing happens! I followed all the steps outlined on this GitHub page: https://githu ...

Running various callbacks consecutively from an array in JavaScript

I have a series of functions in an array, each one calling a callback once it's finished. For example: var queue = [ function (done) { console.log('Executing first job'); setTimeout(done, 1000); // actually an AJAX call ...

Transmit a pair of data values to the ajax request

How can I send two parameters to my JavaScript and retrieve them in a PHP file? Here is my HTML: <form method="post" action="testButtonSup.php"> <p> Please choose the service:<br /> <input type="radio" n ...

retrieving the element's height results in a value of 'undefined'

I am attempting to get the height of a specific element, but unfortunately I keep getting undefined. Here is what I have tried: var dl; $(window).load(function(){ dl = $("#dashboard_left").height(); }); $(document).ready(function(){ alert(dl); } ...

A method to use jQuery to replace newlines with commas in user input

Input Processing Challenge <input> Whenever there is multi-line text pasted into the input field, I need to replace newlines (\r, \n, and \r\n) as well as tabs \t with commas ,. This scenario mainly occurs when users copy c ...