user2128912 user2128912 - 5 years ago 836
Javascript Question

How to make a HTML table cell into a editable text box

Basically, I want the the user to click the table and edit the text.

This is the Js Fiddle I followed:

http://jsfiddle.net/ddd3nick/ExA3j/22/

Below you will be able see the code I have put together. I have followed a JS fiddle and thought of using this in my page.

When I double click the cell nothing happens, I am not sure why is not working.

Please help to find what's missing!

<!DOCTYPE html>
<html>
<head>
<title>Table</title>
<script type="text/javascript">

$(function () {
$("td").dblclick(function () {
var OriginalContent = $(this).text();
$(this).addClass("cellEditing");
$(this).html("<input type='text' value='" + OriginalContent + "' />");
$(this).children().first().focus();
$(this).children().first().keypress(function (e) {
if (e.which == 13) {
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function(){
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
$(this).find('input').dblclick(function(e){
e.stopPropagation();
});
});
});

</script>

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

</head>

<body>

<table class="editableTable">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>Shahid</td>
<td>shahid@ssiddique.info</td>
<td>012-234-2432</td>
</tr>
</tbody>
</table>

<a href='http://ssiddique.info'> ssiddique </a>

</body>
</html>

Answer Source

You included your code first and second the jQuery library.

  1. First include the jQuery
  2. Than put your script
  3. You might want to take a look at contenteditable Elements

which would than look pretty much like this:

$(function() {

  var $td = $("td");

  $td.on({
    "keypress" : function(e) {
      if (e.which == 13) {
        e.preventDefault();
        $(this).prop("contenteditable", false);
      }
    },
    "dblclick" : function() {
      $td.not(this).prop("contenteditable", false);
      $(this).prop("contenteditable", true);
    }
  });

});
td, th { padding:5px; }
td[contenteditable=true] { outline: 2px solid #0af; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Code</th>
      <th>Name</th>
      <th>Email</th>
      <th>Phone</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>001</td>
      <td>Shahid</td>
      <td>shahid@ssiddique.info</td>
      <td>012-234-2432</td>
    </tr>
  </tbody>
</table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download