Reputation: 3407
Here's the html:
<div id="parent">
<div id ="child1">
<div id="subchild1">
<input type="text" name="first" value="3">
</div>
</div>
<div id ="child2">
<div id="subchild2">
<input type="text" name="second" value="7">
</div>
</div>
<div id ="child3">
<div id="subchild3">
<input type="text" name="third" value="8">
</div>
</div>
</div>
<div id="result">
Here's the Jquery:
$(function(){
var len = $('#parent > div').length;
for(var i=0; i < len; i++){
var a = $('#subchild'+ [i + 1]).find('input');
$('#result').html(a);
}
});
It always get's the last value. I tried all my best but here's the only code I can do. Maybe someone that can help me.
Upvotes: 0
Views: 73
Reputation: 171679
If all you want is values the following creates an array of those values and uses join()
to separate them in the target div:
var values = $('[id^=subchild] input').map(function(){
return this.value;
}).get();
$('#result').html( values.join('<br>') );
Upvotes: 2
Reputation: 9060
Problem is you're using $('#result').html(a);
as this code will replace the previous value and take only the last result. Use .append
instead like below code :
$(function () {
var len = $('#parent > div').length;
for (var i = 0; i < len; i++) {
// get value of input text
var a = $('#subchild' + [i + 1]).find('input').val();
// every time got value, append those value into result element
// now input value available, see console
console.log(a);
$('#result').append(a);
}
});
Upvotes: 1
Reputation: 506
Change
$('#result').html(a);
to
$('#result').append(a);
.html() replaces everything within that element where .append() just adds to what's already there.
Upvotes: 4
Reputation: 144
What about something like this? values
holds all 3 values.
$(function() {
var len = $('#parent > div').length;
var values = [];
for (var i = 0; i < len; i++) {
var a = $('#subchild' + [i + 1]).find('input').val();
values.push(a);
}
alert(values);
$('#result').html(values.toString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div id="child1">
<div id="subchild1">
<input type="text" name="first" value="3">
</div>
</div>
<div id="child2">
<div id="subchild2">
<input type="text" name="first" value="7">
</div>
</div>
<div id="child3">
<div id="subchild3">
<input type="text" name="first" value="8">
</div>
</div>
</div>
<div id="result"></div>
Upvotes: 1
Reputation: 1496
The reason you're only seeing the last result is because you're equating the html each time and not concatenating it.
$(function(){
var len = $('#parent > div').length;
for(var i=0; i < len; i++){
var a = $('#subchild'+ [i + 1]).find('input');
$('#result').append(a);
}
});
Fiddle: https://jsfiddle.net/1L5v4q3c/
Upvotes: 1