Reputation: 150
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
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
Reputation: 94429
var result = 0;
$("input").each(function(index,value){
result += parseFloat($(this).val());
});
Demo: http://jsfiddle.net/JmsAb/1/
Upvotes: 0
Reputation: 3661
var value = 0;
$('.parent input').each(function() {
value += parseInt($(this).val());
});
Upvotes: 3
Reputation: 6359
You can use each...
var total = 0;
$(".child").each(function() {
total += parseInt($(this).val());
});
Or similar
Upvotes: 6