user7397787
user7397787

Reputation: 1480

Inline edit in table with edit button jquery

Following sample code is for making a row editable with edit button.Totally I have 3 buttons,Initially I am hiding the update button.When I click edit button inline edit should be enabled and when I click update inline edit should be disabled.
I wrote the below code and I am unable to find it what I did wrong?

$('.edit').click(function(){
        var currentTD = $(this).parents('tr').find('td');
        if ($(this).html() == 'Edit') {
            currentTD = $(this).parents('tr').find('td');
            $.each(currentTD, function () {
            $(this).prop('contenteditable', true)
            });
        } else {
            $.each(currentTD, function () {
            $(this).prop('contenteditable', false)
            });
        }
        });

Complete code: Fiddle. Main thing is I am using dynamic data so if I click edit only selected row sholuld be able to enable.please Let me know what I did wrong

Upvotes: 1

Views: 2391

Answers (2)

Nikolay Prokopyev
Nikolay Prokopyev

Reputation: 1312

Name your tr numerically for each row - for example row1, row2, and add class to potentially editable td like .tdCanEdit Then make your Edit buttons named accordingly, i.e. button1, button2. Then create a function, which takes clicked button - extract it's number. Use this number to get a row id. Find each .tdCanEdit classed element in children of your row. Add them your .contenteditable class.

Of course, remove all .contenteditable classes after finishing.

And avoid ($(this).html() == 'Edit') check. Use classes instead (add some extra class to buttons).

Upvotes: 0

vijayP
vijayP

Reputation: 11512

Can you look at below code. Its just your code only with couple of modifications:

https://jsfiddle.net/xcmvzpuk/5/

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

    var editId = $(this).attr('id'); //here we will get id like edit0 and edit1 and so on
    $("#" + editId).hide();
    var number = editId.replace("edit", ""); //grab the number from id
    $("#update" + number).show();//show the corresponding update button

    var currentTD = $(this).parents('tr').find('td');
    //enable the current row
    $.each(currentTD, function() {
      $(this).prop('contenteditable', true)
    });

  });

  $('.update').click(function() {
    var updateId = $(this).attr('id');
    $("#" + updateId).hide();
    var number = updateId.replace("update", "");
    $("#edit" + number).show();

    var currentTD = $(this).parents('tr').find('td');
    //disable the current row
    $.each(currentTD, function() {
      $(this).prop('contenteditable', false)
    });
  });

Upvotes: 1

Related Questions