user1170330 user1170330 - 5 months ago 15
jQuery Question

Adding elements within new TD

I have this table structure:

<table>
<tr>
<td>some column|1</td>
<td>
<input type="text" id="abc|1" />
</td>
</tr>
<tr>
<td>another column|1</td>
<td>
<input type="text" id="def|1" />
</td>
</tr>
<tr>
<td>some column|2</td>
<td>
<input type="text" id="abc|2" />
</td>
</tr>
<tr>
<td>another column|2</td>
<td>
<input type="text" id="def|2" />
</td>
</tr>
</table>


I want the both right columns of the last 2 rows to be added to the right, as a new column.

So that it looks like that:

enter image description here

In my approach (inspired here) the elements are just added within an existing column, instead of creating a new column
td
:

var newVals1 = $("table td:nth-child(2) [id$=2]");

$("table td:nth-child(2) [id$=1]").each(function(ind) {
if (ind < newVals1.length) {
var newElement = newVals1[ind];
$(newElement).parent().parent().remove();
$(this).after($(newElement));
}
});


FIDDLE.

So how can I add the elements within a new
td
?

So instead of:

<td>
<input type="text" id="abc|1">
<input type="text" id="abc|2">
<input type="text" id="abc|3">
</td>


I want:

<td>
<input type="text" id="abc|1">
</td>
<td>
<input type="text" id="abc|2">
</td>
<td>
<input type="text" id="abc|3">
</td>


Simply doing

$(this).after("<td>" + newElement + "</td>")


results in

[object HTMLInputElement]

Answer

Try this:

$("table td:nth-child(2) [id$=2]").each(function(i) {
    var $newCell = $(this).wrap('<td></td').parent();
    var $newRow = $("table td:nth-child(2) [id$=1]").eq(i).parents('tr');
    $(this).parents('tr').remove();
    $newRow.append($newCell);
});

https://jsfiddle.net/9uathy82/5/

Comments