I would like to edit table cell by click on it. I tried but its not updating properly.
When I am trying to update first cell in the first row last column its getting updated. But if i try to update in the middle entire column value getting changed.But for me only one cell value should get changed.
JS:
$(document).ready(function() {
$('.editable').click(function(e) {
var i = 0;
var id = $(this).attr('id');
e.stopPropagation(); //<-------stop the bubbling of the event here
var value = $('#' + id).html();
console.log(id + i);
updateVal('#' + id, value);
});
function updateVal(currentEle, value) {
console.log("Current Element is" + currentEle);
$(currentEle).html('<input class="thVal" maxlength="4" type="text" width="2" value="0" />');
$(".thVal").focus();
$(".thVal").keyup(function(event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val().trim());
//$(currentEle).html($(".thVal").val().trim());
}
});
$(document).click(function() { // you can use $('html')
$(currentEle).html($(".thVal").val().trim());
});
}
});
<body>
<tbody id="itemtab" style="width:100%;height:200px !important;font-size:12px">
<table border="1">
<th>field1</th>
<th>field2</th>
<th>field3</th>
<tr>
<td>10</td>
<td>10</td>
<td id="my1" class="editable">10</td>
</tr>
<tr>
<td>10</td>
<td>10</td>
<td id="my2" class="editable">20</td>
</tr>
<tr>
<td>10</td>
<td>10</td>
<td id="my3" class="editable">30</td>
</tr>
</table>
</tbody>
</body>
So it seems to work just fine if you change the nested event handler from handling a
click
ondocument
to handling afocusout
on.thVal
. e.g. Instead of:Do
JSFiddle here