user1885099
user1885099

Reputation: 150

jquery: get values of all children of a div

I am trying to use jquery to get the values of all children element of a div.

<div class='parent'>
    <input type='text' value='1' class='child' />
    <input type='text' value='2' class='child' />
    <input type='text' value='3' class='child' />
    <input type='text' value='4' class='child' />
</div>

The child inputs are generated with php from db. Their number varies.

I am trying to get something like:

variable = (child1_value + child2_value + child3_value + child4_value + ... + "childX_value");

how can I make this work for whatever number of children?

Upvotes: 3

Views: 13801

Answers (5)

Swarne27
Swarne27

Reputation: 5737

Try this,

$(document).ready(function(){
    var array = [];
    $('.child').each(function(){
       array.push($(this).val()); // store in an array for reuse
    });
    var total = 0;
    for (var i = 0; i < array.length; i++) {
        total += parseInt(array[i]); // sum up values in the array
    }
    alert(total);
});

Upvotes: 3

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

var result = 0;
$("input").each(function(index,value){ 
  result += parseFloat($(this).val());
});

Demo: http://jsfiddle.net/JmsAb/1/

Upvotes: 0

Thomas Ruiz
Thomas Ruiz

Reputation: 3661

var value = 0;
$('.parent input').each(function() {
  value += parseInt($(this).val());
});

Upvotes: 3

Jeff Watkins
Jeff Watkins

Reputation: 6359

You can use each...

var total = 0;

$(".child").each(function() {
    total += parseInt($(this).val());
});

Or similar

Upvotes: 6

Adil
Adil

Reputation: 148110

To add these values.

Live Demo

sum = 0;
$('.parent :input').each(function(){     
      sum+= parseFloat($(this).val());
})
alert(sum);

Upvotes: 1

Related Questions