Jquery - Retrieve the value of a 'td' and insert inside a Text

1

Good evening,

Next, I have a table from which I generate the data from mysql, I want to get the value of td, and insert inside a TEXT that will appear inside the table TD with the value that was there so that it can be edited and updated in the database, I am trying to use JQuery to accomplish such a feat but without success. / p>

I tried something like this:

$(function(){
   $('#ID_DA_TD').click(function(){
      var teste = $('#ID_DA_TD').text();
      $('#ID_DA_TD').html('<input type="text" class="form-control form-control-sm" id="upgrade" style="width:150px;">');
      $('#upgrade').val(teste);
   });
});

I'm sorry for my ignorance but I'm a beginner, vlw.

    
asked by anonymous 22.02.2018 / 00:44

1 answer

1

You do not need to get id (otherwise you will have to create multiple events for each id ). Just click on td . You must also create ids dynamics for the new inputs , otherwise there will be several inputs with the same id , which is wrong. You can create ids different using the index of td .

Also use the .trim() method to wipe the ends of the text.

Edit

Include an auxiliary button to return the original state of td :

$(function(){
   $('table td:not("input")').click(function(e){
      if($(this).find("input").length == 0){
         var idx = $('table td').index(this);
         $(this)
         .html('<input data-original="'+$(this).text().trim()+'" value="'+$(this).text().trim()+'" type="text" class="form-control form-control-sm" id="upgrade'+idx+'" style="width:150px;"><button>X</button>')
         .find('input').focus();
      }else if(e.target.tagName == "BUTTON"){
         $(this).html($(this).find("input").data("original"));
      }
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><tdid="td1">
         texto 1
      </td>
      <td id="td2">
         texto 2
      </td>
   </tr>
</table>
    
22.02.2018 / 02:23