vvr02 vvr02 - 1 month ago 28
HTML Question

How to edit and update td value when double click Jquery

I written a code such that when user double click on td I am appending input type text and adding the value to it and updating if clicks on enter.

Here is the my problem if user double click on td and he is not pressed enter and again he clicked on another td. By that time I have to reset previous value of input type text td and open clicked td and if he clicked on body i.e., other than that input box I need to reset to the previous value.

// Selecting the table th odd elements
$("#div table td").dblclick(function(){
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});

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

$('body').not(".thVal").click(function(){
if(('.thVal').length != 0)
{
$(currentEle).html($(".thVal").val().trim());
}
});
}


Please help me.
I don't want to use jeditable datatable.

Jai Jai
Answer

Here in your case you need .stopPropagation(): http://jsfiddle.net/jFycy/

$(function () {
    $("#div table td").dblclick(function (e) {
       e.stopPropagation();      //<-------stop the bubbling of the event here
       var currentEle = $(this);
       var value = $(this).html();
       updateVal(currentEle, value);
    });
});

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

  $(document).click(function () { // you can use $('html')
        $(currentEle).html($(".thVal").val().trim());
  });
}

Instead doing click on body do the event on document or html which is the parent elem of all others elems.

Comments