costal martignier costal martignier - 5 months ago 10
jQuery Question

JS/jquery - add textbox on doubleclick and update table field(s)

hello dear programmers,

i'm trying to update table fields with ajax.

doubleclick on a table cell, the cell content will be replaced with a textbox and after changing the text, it updates the cell value with the textbox value.

my problem is, the first change works fine, but after the second change, all table cells changed before are updated with the new value and not only the one clicked.

would be great if someone can help me out and point me to right direction.

you can find the whole thing to test on http://jsfiddle.net/bDxDX/3/

$(function () {
$(".doodleEdit").dblclick(function (e) {
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});
});

function updateVal(currentEle, value) {

$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');

var mode = $(currentEle).attr('class').split(' ')[1];

if (mode == 'editDescr') {
alert("editDescr");
} else if (mode == 'addDate') {
alert("addDate");
} else if (mode == 'addVote') {
alert("addVote");
}

$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val().trim());
}
});

$(document).click(function () {
$(currentEle).html($(".thVal").val().trim());
});
}


http://jsfiddle.net/bDxDX/3/

many thanks and best regards
costal

Tom Tom
Answer

Does this solve your case ? Please check this jsfiddle -

http://jsfiddle.net/hellomaya/bDxDX/5/

$(function () {
    $(".doodleEdit").dblclick(function (e) {
        e.stopPropagation();
        var currentEle = $(e.target);
        var value = $(e.target).html();

        console.log($(e.target));

        if ($.trim(value) === "") {
            $(currentEle).data('mode', 'add');
        } else {
            $(currentEle).data('mode', 'edit');
        }
        updateVal(currentEle, value);
    });
});

function updateVal(currentEle, value) {

    $(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');

    var mode = $(currentEle).data('mode');
    alert(mode);

    $(".thVal").focus();
    $(".thVal").keyup(function (event) {
        if (event.keyCode == 13) {
            $(this).parent().html($(this).val().trim());
            $(".thVal").remove();
        }
    });
}

$(document).click(function (e) {
    if ($(".thVal") !== undefined) {
        if ($(".thVal").val() !== undefined) {
            $(".thVal").parent().html($(".thVal").val().trim());
            $(".thVal").remove();
        }
    }
});
Comments