Sateesh2607 Sateesh2607 - 5 months ago 18
CSS Question

Editing HTML table row data

Hello Folks..,

I am getting error while updating text field values. When I update one text field, the remaining are all updated automatically with same value.

Here is the link contains my source code:

http://jsfiddle.net/jFycy/284/

My requirement is to update that particular field only.

$(function () {
$(".inner, .inner2").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 + '" />');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val().trim());
}
});

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

Answer

You can do something like this

$(function() {
  $(".inner, .inner2").dblclick(function(e) {
    // check text input element contains inside
    if (!$('.thVal', this).length)
    // if not then update with the input element
      $(this).html(function(i, v) {
      return '<input class="thVal" type="text" value="' + v + '" />'
    });
  }).on({
    // bind keyup event 
    'keyup': function(event) {
      // on enter key update the content
      if (event.keyCode == 13) {
        $(this).parent().html($(this).val().trim());
      }
    },
    'blur': function() {
      // if focus out the element update the content with iput value
      $(this).parent().html($(this).val().trim());
    }
  }, '.thVal');
});
.inner {
  background: red;
}
.inner2 {
  background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner">1</div>
<div class="inner2">1</div>
<div class="inner">1</div>


Or much more simpler method with a contenteditable attribute.

.inner {
  background: red;
}
.inner2 {
  background: grey;
}
<div contenteditable class="inner">1</div>
<div contenteditable class="inner2">1</div>
<div contenteditable class="inner">1</div>

Comments