Reputation: 845
Html code:
<form>
<table>
<tr>
<td>Value</td>
<td class="to">ABC</td>
</tr>
</table>
</form>
<div class="from" style="display:none;">
<label>
<input type="text" value="" placeholder="Number"/>
</label>
</div>
and this javascript code:
$(document).ready(function(){
var values = [12,11,15];
var cloned = $('div.from').find('label').clone();
$('td.to').empty();
for(var i=0;i<values.length;i++){
cloned.find('input').val(values[i]);
//console.log(cloned);
console.log(cloned.find('input').val());
$('td.to').append(cloned);
}
});
I am here trying to clone the nested 'label
' from the hidden div 'div.from
' and set one of the value from the 'values
' array and append to empty 'td.to
' using the same cloned object. As far as I know, the last value of the array seems to be appended after cloning. The result should have been three cloned nested labels with value populated in the input box from the 'values
' array.
Here is jsbin link : http://jsbin.com/yuyaqu
Upvotes: 1
Views: 448
Reputation: 337560
You need to clone()
once per iteration, so put that line within the for
:
var values = [12,11,15];
$('td.to').empty();
for (var i = 0; i < values.length; i++){
var cloned = $('div.from').find('label').clone();
cloned.find('input').val(values[i]);
$('td.to').append(cloned);
}
Upvotes: 1