2

I have a list of input boxes, now I need to calculate the total of all values entered in input boxes with the following naming convention pre[0],pre[1],pre[2] etc.

Is this possible with Jquery and how?

Elitmiar
  • 35,072
  • 73
  • 180
  • 229
  • possible duplicate of [jQuery calculate sum of values in all text fields](http://stackoverflow.com/questions/2417553/jquery-calculate-sum-of-values-in-all-text-fields) – Reigel Gallarde Sep 13 '10 at 09:27
  • 1
    @Reigel The problem is that they aren't *exact* duplicate. That one needs it to be triggered on the `blur` event, while this one requires that selector. You **can** conceivably merge them, but keep doing this to subtlety different questions and we'll end up with the jQuery documentation page. – Yi Jiang Sep 13 '10 at 09:31

2 Answers2

10

Would something like this work?

var sum = 0;

$('input[name^="pre"]').each(function(){
    sum += parseFloat(this.value);
});

^= is the Attribute Starts With Selector.

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
0

I would do it like this

var sum = 0;

find("input[name*='pre']").each(function(index) {

sum = sum + this.val();

 })
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311