Solved

jQuery Count Totals

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

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Why do we like using grid based layouts in website design? Let's look at the live examples of websites and compare them to grid based WordPress themes.
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.
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…
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.

708 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

17 Experts available now in Live!

Get 1:1 Help Now