How to dynamically add a new column to an HTML table

html, javascript, jquery

Solution

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('<td>Col+'iter+'</td>');
         }else{
             trow.append('<td><input type="checkbox" name="cb'+iter+'"/></td>');
         }
     });
     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.

Problem

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 button. The user will enter the column header in a textbox. How can I achieve this? If the user adds 4 rows, the `Add a new Column` button should take care of all the existing rows (adding checkbox in each one). update I'm looking to add column name and checkbox at row level. so I've added the text box in which the user will input the column name: http://jsfiddle.net/fmuW6/10/ ``` <input type=text placeholder='columnname'/> <button type="button" id="btnAddCol">Add new column</button></br></br> ``` so then when user clicks the button the columnname should be the value in the textbox and at the row level should be checkboxes. So basically the new column should be appended to all `tr` in the table except the first row since that is the column names

Original source