Editable jQuery table cell

I looked at some editable table plugins, but I'm not sure if they are really necessary for my needs. All I want to do is click on the td element, grab the current value, then change the td html to the + input button, and when I click the button, delete the input and button and put the new text in td. Here is what I have, and it does not work at all. when you click on td, the whole table disappears and is replaced by an input.

Here is the JS:

    var selectedObj;

  $('td').click(function(e){
      // Handle the click

     if ($('#currentInput').length == 0)
     {
          selectedObj = $(this);
        var currentValue = $(this).text();
        var newValue = currentValue;

        $(this).html("<input id='currentInput' type='text' value='"+currentValue+"'/> <button onclick='setNewValue()'>Set</button>");
     }

  });
  function setNewValue()
  {
            var newValue = $('#currentInput').val();

        selectedObj.html('');
            selectedObj.text(newValue);
  }

And HTML:

<p> 
<table id='transitTable' border="0" cellspacing="2" cellpadding="2" class='display' width="400">
<tr id='1'>
<td class="etsHeader etsLeft">H1</td>
<td class="etsHeader etsLeft">H2</td>
<td class="etsHeader etsLeft">H3</td>
<td class="etsHeader etsLeft">H4</td></tr>
<tr id='2'>
<td class="etsValue etsOdd etsLeft">R1</td>
<td class="etsValue etsOdd etsLeft">R1</td>
<td class="etsValue etsOdd etsLeft">R1</td>
<td class="etsValue etsOdd etsLeft">R1</td></tr>
<tr id='3'>
<td class="etsValue etsEven etsLeft">R2</td>
<td class="etsValue etsEven etsLeft">R2</td>
<td class="etsValue etsEven etsLeft">R2</td>
<td class="etsValue etsEven etsLeft">R2</td></tr></table></p>
+3
source share
2 answers

This is because you are replacing tdwith a tag inputthat is not valid in this context.

violation code

$(this).html("<input id='currentInput' type='text' value='"+currentValue+"'/> <button onclick='setNewValue()'>Set</button>");

Try .append()before tdor wrap the values tdin another tag.

+2
source

Why don't you try contentEditable = true,

Check here

+4
source

All Articles