Solved

jQuery Count Totals

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn how to count occurrences of each item in an array.
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.

867 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now