I have the following code to enable inline editing of td cells:
$('.edit_td').click(function(e) {
e.stopPropagation();
resetEditedCells();
$(this).addClass('active').html('<input type="text" value="' + $(this).html() + '">');
});
function resetEditedCells() {
$('.edit_td.active').html(function() {
return $(this).find('input').val();
});
}
$(document).click(function() {
if($('.edit_td').hasClass('active')) {
var fisk = $('.active input[type=text]').val();
$('.edit_td').find('input').hide().html(fisk);
}
});
I have two problems:
When the TD has transformed to an input field, I can't write a new text in it. I cant edit the text.
When I click outside the table, I want the input field to transform back to the td with its original text value, but it does not do that with my code above. The input field is removed, but the text is also removed/hidden. I only want the input to disappear.
Anyone who can help me?
Here is a working version of what you wanted.
const $edits = $('.edit_td');
$edits.on('click', function(e){
e.stopPropagation();
const $this = $(this);
if(!$this.hasClass('active')){
$this.addClass('active');
const val = $this.html();
console.log(val);
$this.html(`<input type="text" value="${val}"/>`);
}
});
function removeActive() {
$edits.each(function() {
const $this = $(this);
if ($this.hasClass('active')) {
const val = $this.find('input').val();
$this.empty();
$this.html(val);
$this.removeClass('active');
}
});
}
$(document).on('click', removeActive);
table {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="edit_td">Test 123</td>
</tr>
<tr>
<td class="edit_td">Test 456</td>
</tr>
<tr>
<td class="edit_td">Test 789</td>
</tr>
</table>