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?

2
  • possible duplicate of jQuery calculate sum of values in all text fields Commented Sep 13, 2010 at 9: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. Commented Sep 13, 2010 at 9:31

2 Answers 2

10

Would something like this work?

var sum = 0;

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

^= is the Attribute Starts With Selector.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, yours is better than mine.
0

I would do it like this

var sum = 0;

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

sum = sum + this.val();

 })

2 Comments

it's this.value or $(this).val()
this.value is better because it does not create an additional jQuery object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.