Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add a new column to an HTML table

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

like image 886
Anthony Avatar asked Feb 19 '13 17:02

Anthony


People also ask

How dynamically add data to a table in HTML?

The insertRow() method creates an empty <tr> element and adds it to a table. The insertRow() method inserts the new row(s) at the specified index in the table. Note: A <tr> element must contain one or more <th> or <td> elements.

How do you add a new column to a table in HTML?

Creating Tables in HTML You can create a table using the <table> element. Inside the <table> element, you can use the <tr> elements to create rows, and to create columns inside a row you can use the <td> elements. You can also define a cell as a header for a group of table cells using the <th> element.


1 Answers

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.

like image 97
GNi33 Avatar answered Sep 24 '22 15:09

GNi33