Find input values with same class

Asked

Viewed 484 times

0

How can I act to sum the values of inputs of the same class being that, the number of inputs does not have a standard, ie, can be that time the class p1 has 5 instances, hour 1.

The structure would look something like this:

<input type='text' class='p1' />
<input type='text' class='p1' />
<input type='text' class='p1' />

<input type='text' class='p2' />
<input type='text' class='p2' />
<input type='text' class='p2' />

<input type='text' class='p3' />
<input type='text' class='p3' />
<input type='text' class='p3' />

2 answers

2


Can make a each in the items corresponding to the class sought.

Example:

var sum_p1 = 0;
$('.p1').each(function (){
  // O + antes do $ é para converter o valor para inteiro, uma vez que ele retorna string.
  sum_p1 += +$(this).val();
});

You can also create a generic function to do this:

function sumInputValuesByClass(c){
  var sum = 0;
  $('.'+c).each(function (){
    sum += +$(this).val();
  });
  return sum;
}

1

Hello, you are missing the name which in case should be an array. And the value of the input, which I understand, is what you want to add:

<input name="p1[]" value="1" type='text' class='p1' />
<input name="p1[]" value="2" type='text' class='p1' />
<input name="p1[]" value="3" type='text' class='p1' />

Then you do the sum in jQuery, which can be triggered by any other action. Here follows in the document load and will bring an Alert with the number 6, which is the sum of the values:

<script type="text/javascript">
$(document).ready(function() {
    p = $('.p1');
    soma = 0;
    for(i=0; i<p.length; i++) {
        soma += Number(p[i].value);
    }
    alert(soma);
})
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.