I’m working on a project that requires me to make cells in a table editable when the equivalent row in another table has been clicked. The problem I am having is that I can’t get it to only make a single row in the updateable table editable, instead it is making every cell of every row editable.
Here is a sample on jsfiddle demonstrating the issue: http://jsfiddle.net/z9qtH/24/
In this sample if you click “Row 1” in the table at the top, the first row of the table below should have the contents of its cells replaced with inputs. Instead, both rows in the bottom table are becoming editable.
Code
HTML:
<table border="1">
<tr>
<td class="editable">Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
</table>
<table class="updateable" border="1">
<tr>
<td>1 - 1</td>
<td>1 - 2</td>
<td>1 - 3</td>
</tr>
<tr>
<td>2 - 1</td>
<td>2 - 2</td>
<td>2 - 3</td>
</tr>
</table>
Javascript:
function replaceRowCellContentsWithInput(row) {
$("td", row).each(function() {
$(this).html('<input type="text" value="' + $(this).html() + '" />');
});
}
$(document).ready(function() {
$("td.editable").click(function() {
var cell = $(this);
var rowIndex = cell.parent().index();
var table = $("table.updateable");
replaceRowCellContentsWithInput(table.children(rowIndex));
});
});
Your line:
table.children(rowIndex)selects the (possiblethead) andtbodyelements. Even if they do not appear in your HTML, the browser always inserts atbody.If you replace that with (for instance)
$('tr', table)[rowIndex]you are sure you actually are selecting the rows inside the table.