Solved

jQuery Count Totals

Posted on 2013-12-05
3
472 Views
Last Modified: 2013-12-05
As per my last question:
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_28310852.html

I have several counters on my page that I can increase and decrease via a + and - sign.  There are several on the same page.

Now I'm looking for a way to have a total counter at the bottom of the page that sums all the quantities in realtime as I add or subtract from the counters on my page.
0
Comment
Question by:N R
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 30

Accepted Solution

by:
Alexandre Simões earned 250 total points
ID: 39698691
Here's a solution: http://jsfiddle.net/AlexCode/ZzYHt/2/

I picked RainerJ code as it's the one marked as accepted solution.
Be aware that on RainerJ's original code, the variable fieldName is declared twice without the var before.
This makes it a global scope variable which is not good.
In my code I fixed that also.

Probably this is not the code exactly that you're using but you can also improve it and it might be more or less important depending on the amount of elements that you have on the page.

Here's the full code as a reference.
I only added the Total element on the HTML and changed the javascript as necessary.
The processTotal() function is being called at the end so that the total is displayed upon page_load.

HTML
<form id='myform' method='POST' action='#'>
    <input type='button' value='-' class='qtyminus' field='quantity1' />
    <input type='text' id='quantity1' value='0' class='qty' />
    <input type='button' value='+' class='qtyplus' field='quantity1' />
    <br/>
    <input type='button' value='-' class='qtyminus' field='quantity2' />
    <input type='text' id='quantity2' value='4' class='qty' />
    <input type='button' value='+' class='qtyplus' field='quantity2' />
    <br/>
    <input type='button' value='-' class='qtyminus' field='quantity3' />
    <input type='text' id='quantity3' value='99' class='qty' />
    <input type='button' value='+' class='qtyplus' field='quantity3' />
    <br/>
    
    <span>Total: </span><span id="total">--</span>
</form>

Open in new window

Javascript
jQuery(document).ready(function () {
    // This button will increment the value
    $('.qtyplus').click(function (e) {
        // Stop acting like a button
        e.preventDefault();
        // Get the field name
        var fieldName = $(this).attr('field');
        // Get its current value
        var currentVal = parseInt($('#' + fieldName).val());
        // If is not undefined
        if (!isNaN(currentVal)) {
            // Increment
            $('#' + fieldName).val(currentVal + 1);
        } else {
            // Otherwise put a 0 there
            $('#' + fieldName).val(0);
        }
        
        $('#' + fieldName).trigger('change');
    });
    // This button will decrement the value till 0
    $(".qtyminus").click(function (e) {
        // Stop acting like a button
        e.preventDefault();
        // Get the field name
        var fieldName = $(this).attr('field');
        // Get its current value
        var currentVal = parseInt($('#' + fieldName).val());
        // If it isn't undefined or its greater than 0
        if (!isNaN(currentVal) && currentVal > 0) {
            // Decrement one
            $('#' + fieldName).val(currentVal - 1);
        } else {
            // Otherwise put a 0 there
            $('#' + fieldName).val(0);
        }
        
        $('#' + fieldName).trigger('change');
    });
    
    $('input.qty').on('change', function() {
        processTotal();
    });
    
    function processTotal() {
        var total = 0;
        $('input.qty').each(function(idx, item) {
            total += isNaN(item.value) ? 0 : parseInt(item.value);
        });
        
        $('#total').html(total);
    }
    
    processTotal();
});

Open in new window

CSS
.qty {
    width: 40px;
    height: 25px;
    text-align: center;
}
input.qtyplus {
    width:25px;
    height:25px;
}
input.qtyminus {
    width:25px;
    height:25px;
}

Open in new window

0
 
LVL 43

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 250 total points
ID: 39699090
I've updated my answer to your previous question:

http://jsfiddle.net/ChrisStanyon/5gdeh/

The change() function is similar to Alex's example, but the HTML is clean. Invalid HTML and non-standard attributes just bug me, but I guess it's up to you... ;)
0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 39700308
@ChrisStanyon: I agree that your version is better. I chose the other one just because it was the one marked as accepted.

Still you have the same problem as @RainerJ missing a var while declaring qty.
I fixed that and prefixed the variable name with a $. This is a best-practice I use to know just from the variable name that it already holds a jQuery object.

http://jsfiddle.net/AlexCode/5gdeh/4/

Cheers!
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article will inform Clients about common and important expectations from the freelancers (Experts) who are looking at your Gig.
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question