views:

35

answers:

2

Below I have the code that allows me to edit a table row inline. However it edits ALL of the TDs within that row. My problem, along with the code, are stated below. Any help is appreciated.

<tbody> 

    <tr> 
        <th scope="row">Test</th>
        <td class="amount">$124</td>
        <td class="amount" id="" >$154</td>
        <td class="diff">- 754</td>

    </tr>

</tbody> 

The above table is just a sample. What I have been trying to accomplish is, to simply edit the TDs within that particular row, but I need it to disregard the diff TD.

I'm fairly new to jQuery and have got the following code via the help of a jQuery book.

$(document).ready(function() {
  TABLE.formwork('#current-expenses');
});

var TABLE = {};

TABLE.formwork = function(table){
  var $tables = $(table);

  $tables.each(function () {
    var _table = $(this);
    _table.find('thead tr').append($('<th class="edit">&nbsp;</th>'));
    _table.find('tbody tr').append($('<td class="edit"><input type="button" value="Edit"/></td>'))
  });

  $tables.find('.edit :button').live('click', function(e) {
    TABLE.editable(this);
    e.preventDefault();
  });
}

TABLE.editable = function(button) {

  var $button = $(button);
  var $row = $button.parents('tbody tr');
  var $cells = $row.children('td').not('.edit');


  if($row.data('flag')) { // in edit mode, move back to table
    // cell methods
    $cells.each(function () {
      var _cell = $(this);
      _cell.html(_cell.find('input').val());
    })

    $row.data('flag',false);
    $button.val('Edit');
  }
  else { // in table mode, move to edit mode
    // cell methods
    $cells.each(function() {
      var _cell = $(this);
      _cell.data('text', _cell.html()).html('');
   if($('td.diff')){
      var $input = $('<input type="text" />')
        .val(_cell.data('text'))
        .width(_cell.width() - 16);

      _cell.append($input);
   }
    })

    $row.data('flag', true);
    $button.val('Save');
  }
}

I have attempted to alter the code so that it would disregard the diff class TD, but have had no luck so far.

+2  A: 

Add one more line after:

var $cells = $row.children('td').not('.edit').not('.diff');
Sarfraz
That works so far, Thanks. How do I go about appending the `.diff` to the `.edit` because I do require to have them both there ?
Russell Dias
Got it :) Thank you.
Russell Dias
@RussellDias: You are welcome :)
Sarfraz
Delan's answer is exactly what I ended up with.
Russell Dias
@Sarfraz - Your second instance of $cells would seem to overwrite the first one, so $cells would still contain the '.edit' element.
patrick dw
@patrick: I think you are right, i should have written what i did now :)
Sarfraz
+3  A: 

Replace

var $cells = $row.children('td').not('.edit');

with

var $cells = $row.children('td').not('.edit').not('.diff');
Delan Azabani
Thank you. This works perfectly.
Russell Dias