Find input values with the same class

0

How can I act to sum up the values of the inputs of the same class and that the number of inputs does not have a standard, that is, it may 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' />
    
asked by anonymous 16.03.2015 / 15:59

2 answers

1

You can make a each in the elements corresponding to the searched class.

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;
}
    
16.03.2015 / 16:07
1

Hello, the name is missing, which should be an array in the case. And the input value, 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 it follows in the load of the document and will bring an alert with the number 6, that 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>
    
16.03.2015 / 16:15