Reputation: 3132
I want to move a cell in a table to a new row. The table just contains one row with four cells. The third one is the one I need. The cell has to be removed from the existing row so only the new one contains it.
This is my markup:
<table class="sbtable">
<tbody>
<tr class="sbrow">
<td class="first">Blah</td>
<td class="second">Blah</td>
<td class="third">Blah</td>
<td class="last">Blah</td>
</tr>
</tbody>
</table>
JQuery:
function formatSearchBox() {
$(".sbtable").each(function () {
var table = $(this);
var firstRow = $(table).find("tr:first");
var cell = $(firstRow).find("td").eq(2);
var newRow = "<tr></tr>";
$(newRow).append($(cell));
console.log(newRow);
$(newRow).append("<td></td><td></td><td></td>");
$(firstRow).after($(newRow));
});
}
My problem is that the script only inserts a blank <tr></tr>
and I have absolutely no idea why. I need the html like this:
<table class="sbtable">
<tbody>
<tr class="sbrow">
<td class="first">Blah</td>
<td class="second">Blah</td>
<td class="last">Blah</td>
</tr>
<tr>
<td class="third">Blah</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Upvotes: 0
Views: 1301
Reputation: 6411
Your selector was wrong as explained in comments above but the main problem was you that you have to update newRow var as you can see below:
$(newRow).append($(cell));
you need
newRow = $(newRow).append($(cell));
Try this http://jsfiddle.net/aamir/dc6fM/3/
$(".sbtable").each(function () {
var table = $(this);
var firstRow = $(table).find("tr:first");
var cell = $(firstRow).find("td:eq(2)");
var newRow = "<tr></tr>";
newRow= $(newRow).append(cell);
newRow.append("<td></td><td></td>");
$(firstRow).after(newRow);
});
Or try shorter version if you prefer: http://jsfiddle.net/aamir/dc6fM/2/
$(".sbtable").each(function () {
var $table = $(this);
var $cell = $table.find("tr:first td:eq(2)");
$table.append($("<tr>").append($cell,"<td></td><td></td>"))
});
Or even shorter: http://jsfiddle.net/aamir/dc6fM/5/
Upvotes: 2
Reputation: 78710
You have created 3 separate rows:
var newRow = "<tr></tr>";
$(newRow).append($(cell)); // new row created and cell appended to it
$(newRow).append("<td></td><td></td><td></td>"); // a different new row created, 3 cells appended
$(firstRow).after($(newRow)); // yet another row created, empty and appended
Each time you are calling $(newRow)
you create another brand new row.
Instead, save the row to the variable:
var $newRow = $("<tr></tr>");
$newRow.append($(cell));
$newRow.append("<td></td><td></td><td></td>");
$(firstRow).after($newRow);
Upvotes: 2
Reputation: 820
your newRow variable is just a string and using the jquery .append method is not working for you. newRow needs to be a jquery object to be worked on.
var newRow = $("<td></td>");
newRow.append("<td></td><td></td><td></td>");
Notice also in the 2nd line, I am not using $(newRow) as the variable already refers to the Jquery object. I see you are doing that when calling $(table) and $(firstRow).
Upvotes: 1