Reputation: 5784
Can you please take a look at This Demo Fiddle and let me know how I can append values from selected row(s) by checkbox from a table to new dynamic table?
so far I have tried this
var td1 = [];
$('#btn').on('click', function () {
var checkedRows = [];
$(':checkbox:checked').closest('tr').each(function () {
checkedRows.push(
$(this).find('td:gt(0)').map(function () {
return $(this).html();
}).get());
});
for (var i = 0; i < checkedRows.length; i++) {
td1.push(parseInt(checkedRows[i][1]));
td1.push(parseInt(checkedRows[i][5]));
td1.push(parseInt(checkedRows[i][3]));
td1.push(parseInt(checkedRows[i][4]));
}
$('pre.out').text(JSON.stringify(td1));
for (var i = 0; i < checkedRows.length; i++) {
// $('#newTable').append('<tr>');
}
});
But I got lost on dealing with loading from two dimensional array checkedRows
so I tried to first load each row to td1
but still confused!
Please be aware that I am not mean to have all cells value in the new table and it must have only values from same heard. Here is the HTML
<table border="1" width="100%">
<thead>
<tr>
<td></td>
<td>Model 1</td>
<td>Shop 2</td>
<td>Shop 3</td>
<td>Shop 4</td>
<td>Shop 5</td>
<td>Shop 6</td>
<td>Shop 7</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type='checkbox' /></td>
<td>Model 1</td>
<td>20000</td>
<td>50000</td>
<td>20000</td>
<td>88000</td>
<td>44000</td>
<td>30000</td>
</tr>
<tr>
<td><input type='checkbox' /></td>
<td>Model 2</td>
<td>20000</td>
<td>50000</td>
<td>20000</td>
<td>88000</td>
<td>44000</td>
<td>30000</td>
</tr>
</tbody>
</table>
<br />
<input id="btn" type="button" label="button" value="get rows" />
<pre class="out"></pre>
<table border="1" width="100%">
<thead>
<tr>
<td>Shop 2</td>
<td>Shop 6</td>
<td>Shop 4</td>
<td>Shop 5</td>
</tr>
</thead>
<tbody id="newTable">
</tbody>
</table>
Thanks
Upvotes: 0
Views: 24
Reputation: 21465
You have done the harder part, now with all checked row's data in the array, you can use append() and create the tr/td code for it:
for (var i = 0; i < checkedRows.length; i++) {
$('#newTable').append('<tr>' +
'<td>' + checkedRows[i][1] + '</td>' +
'<td>' + checkedRows[i][5] + '</td>' +
'<td>' + checkedRows[i][3] + '</td>' +
'<td>' + checkedRows[i][4] + '</td>' +
'</tr>');
}
Bonus: If you want to avoid duply, just change this lines:
$(':checkbox:checked').closest('tr').not(".copied").each(function() {
$(this).addClass("copied");
Fiddle. Then you can disabled the ckeckbox or whatever you want to show user he can't copy that row anymore.
Upvotes: 1