Friday, May 22, 2009

Remove n’th table column - jQuery plugin

My usual short Friday post. Today I would like to share with you a new utility I wrote to work with HTML tables. We already have jQuery functions to add table row, remove table row (on user click), add table row number plugin and now here is jQuery code to remove table column.

jQuery utility to remove table’s n’th column:

$.fn.removeCol = function(col){
    // Make sure col has value
    if(!col){ col = 1; }
    $('tr td:nth-child('+col+'), tr th:nth-child('+col+')', this).remove();
    return this;
};

Just add this code to your javascript file and use it in your jQuery code like this:

// Remove all table's second columns
$('table').removeCol(2);

// Remove table's first column (default)
$('table').removeCol();

The function takes column number to delete as an argument and removes that column. If you don’t supply any column number it removes the first table column by default.

9 comments:

  1. Thanks....its really help to me
    - Damith -

    ReplyDelete
  2. Will this work even if the table has cells that span columns? (<td colspan="2">)

    ReplyDelete
  3. @Anonymous, happy to help.

    @John, it does not. But thanks for pointing it out. I will try to add the feature. Thanks again...

    ReplyDelete
  4. Really thanks for your code it helped me a lot :).

    I just wanted to point out that, this code does not work properly if there is rowspan attribute for any row so be careful.

    ReplyDelete
  5. In order to support chainability, can I suggest you add:

    return this;

    before closing the function?

    ReplyDelete
  6. Thanks. This was exactly what I needed.

    ReplyDelete
  7. @Anonymous, glad it helped. I will try to add this feature in the future.

    @Grant Drury-Green, thanks for noting. Added it into the code.

    @Anonymous, no problems.

    ReplyDelete
  8. hi,

    i have a requirement as i need to remove particular column using jquery and later i need to attach that column in the same place where i removed earlier.

    Everybody giving examples on how to remove a column from the table but nobody giving a thought on how to replace that column in same position

    help would be graceful

    ReplyDelete
  9. $.fn.addCol = function(col){
    // Make sure col has value
    if(!col){ col = 1; }
    $('td:nth-child('+col+'),th:nth-child('+col+')', this).each(function(index,value){
    var cloneCell = $(value).clone(true);
    cloneCell.insertAfter($(value));
    });
    return this;
    };

    $(".addCol").click(function(){
    $("#table1").addCol(index);
    });

    can you help me? he duplicate but only with origin table value.
    if i add col, modify value(textarea) and click again, it add a new col but oldest value

    thanks

    ReplyDelete