How to Edit HTML table cell in inline using Jquery

Kathirvel Appusamy picture Kathirvel Appusamy · Dec 8, 2014 · Viewed 14.7k times · Source

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.

Fiddle Here

JS:

Answer

dfsq picture dfsq · Dec 8, 2014

The problem is that $(document).click handler is not always reached because sometimes event bubbling is prevented with e.stopPropagation(); from $('.editable').click event.

Optimized and fixed code:

$('.editable').click(function (e) {
    e.stopPropagation();
    var value = $(this).html();
    updateVal(this, value);
});

function updateVal(currentEle, value) {
    $(currentEle).html('<input class="thVal" maxlength="4" type="text" width="2" value="' + value + '" />');
    $(".thVal", currentEle).focus().keyup(function (event) {
        if (event.keyCode == 13) {
            $(currentEle).html($(".thVal").val().trim());
        }
    }).click(function(e) {
        e.stopPropagation();
    });

    $(document).click(function() {
        $(".thVal").replaceWith(function() {
            return this.value;
        });
    });
}

Demo: http://jsfiddle.net/8acoz3fv/4/