开发者

jQuery addition of multiple text box values

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.


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜