Solved

jQuery Count Totals

Posted on 2013-12-05
3
441 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
  • 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

How our DevOps Team Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

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

Suggested Solutions

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Any business that wants to seriously grow needs to keep the needs and desires of an international audience of their websites in mind. Making a website friendly to international users isn’t prohibitively expensive and can provide an incredible return…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

825 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