jQuery Summation: A Step-by-Step Guide

Hello everyone, I am a new member of this forum and I am looking forward to learning and contributing with all of you. I have encountered a problem that I tried to solve on my own but couldn't figure it out. Would anyone be able to lend me a hand? Here is the code snippet I am working on: Jquery:

$(document).ready(function() {
var max_fields      = 10; allowed
var moreprod         = $(".contenedor"); wrapper
var add_button      = $("#e");

var x = 1;
$(add_button).click(function(e){ 
    e.preventDefault();
    if(x < max_fields){
        x++; //text box increment
        $(moreprod).append('<div class="fieldprod"><div id="a"><input type="text" placeholder="Product"></input></div><div id="b" class="csymbol" data-symbol="$"><input id="prices" type="text" placeholder=" 0.00"></input></div><div id="c"><input id="prices" type="text" placeholder="qty"></input></div><div id="d" class="csymbol" data-symbol="$"><p id="qty">0.00</p></div><div id="f" class="removebtn">-</div></div>'); //add input box
    }
});


$(moreprod).on("click",".removebtn", function(e){ 
    e.preventDefault(); $(this).parent('div').remove(); x--;
})

});
HTML:
<div class="result">total</div>
<div class="contenedor">
<div class="fieldprod">
<div id="a">
<input type="text" placeholder="Product"></input>
</div>
<div id="b" class="csymbol" data-symbol="$">
<input id="prices" type="text" placeholder=" 0.00"></input>
</div>
<div id="c">
<input id="prices" type="text" placeholder="qty"></input>
</div>
<div id="d" class="csymbol" data-symbol="$"><p id="qty">0.00</p></div>
<div id="e">+</div>
</div>
</div>
I am dynamically creating three inputs and two divs to form a row. However, I need help in summing up the values from two inputs (c = a + b) within each row. If I add a new row, I want to make the sum of values in that row (g = e + f), and then calculate the total sum (total = c + g). Can anyone assist me with this task? Thank you in advance for your help, and I apologize for any language errors in my message.

Answer №1

  1. It is recommended to use classes instead of replicating the id, as it should be unique in the document.
  2. To perform calculations, capture the change event of the input element.

Below is the script to handle these functionalities:

$(document).ready(function () {
    var max_fields = 10;
    var moreprod = $(".contenedor");
    var add_button = $("#e");
    var grandTotal = $('#grand-total');

    var x = 1;
    $(add_button).click(function (e) {
        e.preventDefault();
        if (x < max_fields) {
            x++;
            $(moreprod).append('<div class="fieldprod"><div><input type="text" placeholder="Product"></input></div><div class="csymbol" data-symbol="$"><input class="price" type="text" placeholder=" 0.00"></input></div><div><input class="quantity" type="text" placeholder="qty"></input></div><div class="csymbol" data-symbol="$"><p class="product-total">0.00</p></div><div class="removebtn">-</div></div>');
        }
    });


    moreprod.on("click", ".removebtn", function (e) {
        e.preventDefault();
        $(this).closest('.fieldprod').remove();
        x--;
        moreprod.find('.price').first().trigger('change');
    }).on('change', '.price, .quantity', function(){
        var group = $(this).closest('.fieldprod'),
            quantity = +group.find('.quantity').val(),
            price = +group.find('.price').val(),
            total = group.find('.product-total');

        total.text( (quantity*price).toFixed(2) );

        var grand = moreprod
                        .find('.product-total').get()
                        .reduce(function(p,v){
                            return p + +$(v).text();
                        },0);
        grandTotal.text(grand.toFixed(2));

    });

});

You can view a working demo at http://jsfiddle.net/gaby/9tp5aycy/

Answer №2

In order to dynamically add and remove rows with products in a shop software, it is crucial to ensure that each ID value is unique globally.

There are several approaches to achieve this goal:

  1. Create unique IDs such as x1, x2, x3, etc.
  2. Erase all IDs and rely on CSS selectors to access the fields http://api.jquery.com/category/selectors/
  3. Implement other solutions...

Another important issue to address is the functionality of the remove button. As it stands, only the first row may be deletable due to having just one remove handler registered. It would be wise to register the remove handler immediately after appending each row to ensure proper deletion functionality for all rows.

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

Why is my CSS not recognizing the animation I specified for it to play?

I can't seem to get the simple animation I added to my code working properly. <div class="phone-center"> <div class="phone"> </div> </div> .phone-center { display: flex; justify-content: ce ...

The autocomplete feature in my jquery textbox is malfunctioning

Hey everyone, I'm fairly new to jquery and currently in the process of learning it. I'm attempting to create an autocomplete textbox feature using jquery. However, I seem to be encountering an error that I'm not able to identify. Whenever I ...

Is there a way to align the image next to the form and ensure they are both the same size?

I've been struggling to resize the image to match the form size, but I can't seem to get it right. Can anyone provide me with some guidance on this issue? I have obtained this contact form from a website that I plan to modify slightly, but I need ...

Utilizing jQuery for updating values within an XML document

Upon receiving an XML-like string through a jQuery $.ajax() get request, I encountered issues due to its invalid format preventing the use of dataType:'xml' or $.parseXML(). Despite this, I managed to traverse the xml string successfully using jQ ...

Searching through a current array to select the sixth element, using jQuery or JavaScript

Currently, I am attempting to iterate over the provided array that has been stored in: var mobileNavArray = jQuery.makeArray(mobileNavItems); The goal is to retrieve item 6, which happens to be the final item in the array in order to reverse the event.pr ...

Stylish progress bar using CSS animations

I am trying to make the progress bar expand from 0% width to 50% width in a span of 2 seconds. Here is the code I have written: <style> #progressbar { background-color: #000000; border-radius: 8px; padding: 3px; width: 40 ...

What is the reason behind caching form data in an ajax call?

After the first successful submission, I am facing an issue where the original form data is being re-sent even when new values are submitted for a second attempt. How can I reset and reload the data to avoid this problem? I have tried several approaches i ...

What is the best way to transfer information from a client's HTML to a node.js server?

I needed to transmit JSON data to a node.js server. Here is my server.js code: var http = require('http'); var util = require('util') http.createServer(function (req, res) { console.log('Request received: '); util.log(util. ...

ASP.NET can have issues with the functionality of jQuery AJAX

I'm currently working on an asp.net webform project and I'm looking to implement jQuery ajax functionality. Below is the code snippet I have so far: <asp:Button ID="btn_comment" runat="server" CssClass="contact_btn pull-right" Text="send" OnC ...

Rule for jQuery validation based on variables

I am facing an issue with validation of login asynchronously in my HTML form using the jQuery Validation Plugin. I would like to trigger a request for login validity on blur, and validate it upon receiving a response. Below is the code snippet: var login ...

I am experiencing an issue where the submit button in my HTML form is unresponsive to clicks

Welcome to my HTML world! <form action="petDetails.php" id="animalInput"> <ul> <li> <label for="dogName">Enter Dog's Name:</label><input id="dogName" type="text" name="dogName" /> </l ...

Automatically populate a dropdown menu with options based on the user's birth date

I successfully managed to populate the drop-down fields for months, days, and years. Furthermore, I was able to calculate the age of the user; however, I have restricted it to a maximum of 13 years. Check out the code snippet below: $('#reg-yr' ...

Solid white border encasing the full page

While I know there have been similar questions asked before, I believe mine is unique because I haven't found a solution anywhere. Recently, I started a new project in React. I decided to remove App.css and index.css, and created a single component wh ...

"Troubleshooting the ERR_SPDY_PROTOCOL_ERROR issue with Ajax and .NET Web

Encountering a perplexing issue while attempting to make Ajax calls to a .NET Web Api hosted on IIS on Microsoft Azure. After properly applying my SSL certificate from Let's Encrypt to the website, an error arises when trying to execute an ajax call: ...

Using cakePHP to submit a form using ajax

While submitting a form using ajax and attempting to return a json response, I encountered an issue of receiving a missing view error. Adding autoResponder=false resulted in no response at all. This is happening while working with cakephp 2.5 In the same ...

Incorporate Web-GL sandbox effects into an HTML webpage

I am searching for a method to showcase a Web-gl shader obtained from GLSL Sandbox on the background of an HTML page. Yet, it seems there is no simple embeddable API available. How can I accomplish this task? Can I integrate this specific Shader into an H ...

Text Box: Add a touch of flair with resizing

One interesting feature on my webpage is a textarea that can be resized using resize:both; I am looking for a way to apply a specific style to this textarea only when the user resizes it. While I would prefer to achieve this with CSS alone, it seems like ...

Retrieving a designated value from a jquery object sent via an ajax call

Currently, I have a setup where clicking on a link sends the link's ID via AJAX to a coldfusion page for querying and returning an object. The jquery function in use is: $(".thelink").click(function(){ var link_id = $(this).attr("id"); var ...

How can I create editable text using typed.js?

How can I achieve the same text animation effect on my website as seen on the homepage of ? I want to utilize the library available at . Specifically, how do I stop the animation when the text is clicked, allowing users to input their own text? Below is ...

Materialize Modal Event fails to trigger

I'm experiencing an issue with my custom-script.js file $(document).ready(function () { $('.modal').modal({ onOpenStart() { console.log("Open Start"); }, onOpenEnd() { console.log("Open End"); } ...