How to dynamically add a new column to an HTML table

前端 未结 5 1031
一生所求
一生所求 2020-12-14 02:03

I have a table to which I am currently dynamically adding rows: http://jsfiddle.net/fmuW6/5/

Now I\'d like to add a new column to the table as well with a click of a

5条回答
  •  难免孤独
    2020-12-14 02:18

    I updated your fiddle with a small example how you could do that.

    jsFiddle - Link

    var myform = $('#myform'),
        iter = 0;
    
    $('#btnAddCol').click(function () {
         myform.find('tr').each(function(){
             var trow = $(this);
             if(trow.index() === 0){
                 trow.append('Col+'iter+'');
             }else{
                 trow.append('');
             }
         });
         iter += 1;
    });
    

    This would add a new column to every row, including an count-variable that gets applied to the first row as name and to the name-attribute of the checkboxes on the following rows.

    Consider using th - elements for the table header, that way you wouldn't need the index-check i'm making and it would be more semantically correct.

    I left out the part where the user would put in a name for the column, but as you see, you could just replace the iter - value with that in the end.

提交回复
热议问题