jason jason - 1 year ago 48
jQuery Question

Creating editable table which is generated by JSON

I have this function which generates a table of some words correctly :

function show(json) {
var content = '<table id = "myTable" border = 1>';
var counter;
for (counter = 0; counter < json.length; counter++) {
content += '<tr><td class = "topics">' + json[counter]['topic_name'] + '</td>'
'</tr>';
}
content += '</table>';
$('#table_here').append(content);
}


I want to make this table editable, so that when a user clicks on a cell on a table he should edit that cell. So I wrote this with the help of a tutorial online :

function show(json) {
var content = '<table id = "myTable" border = 1>';
var counter;
for (counter = 0; counter < json.length; counter++) {
content += '<tr id =' + counter + ' class="edit_tr"><td class = "edit_td"><span id = "first_' + counter + '" class="text">' + json[counter]['topic_name'] + '</span><input type="text" value="' + json[counter]['topic_name'] + '" class="editbox" id = "first_input_' + counter + '" /&gt;></td>'
'</tr>';
}
content += '</table>';
$('#table_here').append(content);
}


When I open this page both word in the cells and the word in the box in that cell appear at the same time.And when I click on somewhere on the page the boxes disappear and only words remain, but nothing happens when I click on the words. How can I fix this?
I get the codes from this tutorial : http://www.9lessons.info/2011/03/live-table-edit-with-jquery-and-ajax.html

Answer Source

I dunno what error you're facing but here's a demo. In the demo, I've used an array of colors which look like this :

[
 {
  "colorName": "red",
  "hexValue": "#f00"
 },
 {
   "colorName": "green",
   "hexValue": "#0f0"
 },
 .. so on
]

You need two click functions :

  1. To show the text box when you click on the color:

    $(document).on("click", ".edit_td", function () {
       //reset to default, hide every input and show span in table
       $("input:text").hide();
       $(".text").show();
       $(this).find("span").hide().end().find("input:text").show();
    });
    
  2. To hide the textbox and show span when clicked anywhere other than table

    $(document).on("click", function (event) {
      var $target = $(event.target);
      if ($target.closest("table").length == 0) {
        var $input = $("input:text:visible");
        var value = $input.val();
        $input.closest("td").find(".text").text(value).show();
        $input.parent().hide();
      }
    

    });

Edit :

Added a keyup handler for the input button attached to it:

$(document).on("keyup", "input:text", function (e) {
  if (e.which === 13) {
    var value = $(this).val();
    $(this).closest("td").find(".text").html(value).show();
    $(this).parent().hide();
    return false;
  }
});

Click on the demo on top to see the update :)

Hope this helps :)

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