ArticleZip > Jquery Sum Of Multiple Input Fields If Same Class In One Input

Jquery Sum Of Multiple Input Fields If Same Class In One Input

If you ever found yourself needing to calculate the total sum of multiple input fields that share the same class using jQuery, you've come to the right place! In this article, we'll guide you through a practical "how-to" on achieving just that with ease.

First things first, let's understand the scenario. Imagine you have a form with several input fields that all belong to the same group, identified by a common class name. Your goal is to dynamically calculate the sum of the values entered into these input fields in real-time without any page refresh. Exciting, right?

To begin, ensure you have jQuery included in your project. If you haven't already added it, you can include it from a content delivery network (CDN) like so:

Html

Now, let's dive into the JavaScript part. Below is a simple script that demonstrates how to calculate the sum of input values with the same class:

Javascript

$(document).ready(function() {
    $('.your-input-class').on('input', function() {
        let total = 0;
        $('.your-input-class').each(function() {
            let value = parseFloat($(this).val()) || 0;
            total += value;
        });
        $('#result').text(total);
    });
});

In this script:
- We wait for the document to be fully loaded before executing our code.
- We target the input fields by their shared class ('.your-input-class').
- We use the jQuery 'on' method to listen for input events on these fields.
- We iterate over each input field using the 'each' method.
- We extract the numerical value from each field using 'parseFloat' and add it to the 'total' variable.
- Finally, we update the text content of an element with an id of 'result' to display the calculated total.

Don't forget to adjust the class name ('.your-input-class') and the target element id ('#result') in the script to match your specific HTML structure.

Now, let's put this into action! Create your HTML form with input fields sharing the same class, and an element where you want the total sum to be displayed:

Html

<p>Total Sum: <span id="result">0</span></p>

Voilà! You now have a functional solution to dynamically calculate the sum of multiple input fields with the same class using jQuery. This nifty trick can enhance the interactivity of your forms and provide users with instant feedback as they input values. Happy coding!