views:

63

answers:

1

Hi all,

I have a new task to do and im not sure the best way to approach it with jQuery.

Basically a client wants 'x' amount of text boxes (for quantity) each with a plus/minus button/icon to the side of it and as you click on each one, all the relative fields update.

e.g. (if there were 3 options in a page)

qty [ 0 ] + -
qty [ 0 ] + -
qty [ 0 ] + -

Total of all the above [ 0 ]

I use jQuery a lot but im not sure where to start with this one.

Any advice would be much appreciated.

Adi.

A: 

If you add a CSS class to all the input fields that you need to sum, you could then attach a change event handler to them all that took care of updating the total:

$('input.qty').change(function() {       
    // Loop through all input's and re-calculate the total
    var total = 0;
    $('input.qty').each(function(){
        total += parseInt(this.value);
    });

    // Update the total
    $('#total').val(total);
);

You can see it in action here.

Notes

  1. I've left out the + and - buttons. These could just be links that increment/decrement their associated input's value as needed.
  2. The update total uses parseInt to cast from string to int. It would be up to you to make sure the input's value is a valid integer.
Pat
Hi Pat,There is one issue I see with your answer. If I have '10' and '10' in ther first 2 boxes, the answer is '20' which is correct.However, if I then add change the second box to '20' (trying to make the total '30') it comes up as '40' (as its adding 20 to the current value (which is 20).Hope that makes sense. Is there perhaps an easier way (perhaps using the each attr) to get all teh values and add them?A.
Adi
@Adi whoops - right you are. I've updated my code and link to exactly what you suggested.
Pat