mrdeath4
mrdeath4

Reputation: 161

Make an editable table and save to a database

I have a table that I get from my MySQL base using ajax. The answer from ajax makes the table in a DIV wrapper.

Now I need to edit this table and if it is needed to save it, but I've got several problems.

My plan was to make a $('td').click() append an input and after pressing enter or clicking anywhere the input should be hidden and the clear TD with new value should appear. After that I presss the UPDATE button and save my row to DB. But my JavaScript skills are not so good and I failed even with 100 of examples.

Here is my code:

$('#load').click(function() {
  //the load button - gets the table from DB  
  //here I get some data from the website filter.
  var data = new webmaster(pid, name, email, skype, web, current_offer, lookingfor_offer, anwsered, comment);
  data = JSON.stringify(data);

  $('#aw-wrapper').empty();
  $.ajax({
    type: "POST",
    data: {
      "data": data
    },
    url: "inc/load-web.php",
    success: function(anwser) {
      $('#aw-wrapper').html(anwser);
      TableEdit();
    }

  });

});

function TableEdit() {

  if (i) {
    $('td').click(function() {

      this.onclick = null;
      var td_value = $(this).html();
      var input_field = '<input type="text" id="edit" value="' + td_value + '" />'
      $(this).empty().append(input_field);
      $('input').focus();
      i = 0;
    });
  }
}

But it doesnot work at all. I got many clicks on td instead of one. Maybe I am doing it wrong and it can be realized easier?

Upvotes: 0

Views: 3441

Answers (1)

CumminUp07
CumminUp07

Reputation: 1978

I dont see where i is defined. I changed your function to look like this:

function TableEdit() {
var i = 1;

$('td').click(function() {
        if (i) {
    this.onclick = null;
    var td_value = $(this).html();
    var input_field = '<input type="text" id="edit" value="' + td_value + '" />'
    $(this).empty().append(input_field);
    $('input').focus();
    i = 0;
    }

});
}

if I understand what you want i believe it gives the desired result, however, this is how i would implement this

function TableEdit() {


$('td').click(function() {


    var td_value = $(this).html();
    var input_field = '<input type="text" id="edit" value="' + td_value + '" />'
    $(this).empty().append(input_field);
    $('input').focus();

    $('td').off('click');

    $(this).find('input').blur(function(){
        var new_text = $(this).val();
        $(this).parent().html(new_text);
        TableEdit();
    })

});
}

updated fiddle https://jsfiddle.net/vf2L78p8/2/

Upvotes: 1

Related Questions