?
Solved

jQuery Count Totals

Posted on 2013-12-05
3
Medium Priority
?
507 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:Nathan Riley
[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 1000 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 1000 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

7 Extremely Useful Linux Commands for Beginners

Just getting started with Linux? Here's a quick start guide that has 7 commands that we believe will come in handy.

Question has a verified solution.

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

When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
This article was originally published on Monitis Blog, you can check it here . Today it’s fairly well known that high-performing websites and applications bring in more visitors, higher SEO, and ultimately more sales. By the same token, downtime…
This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…
Suggested Courses
Course of the Month8 days, 3 hours left to enroll

765 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