简体   繁体   中英

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

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.

Modern pure JavaScript solution:

 function addColumn() { [...document.querySelectorAll('#table tr')].forEach((row, i) => { const input = document.createElement("input") input.setAttribute('type', 'text') const cell = document.createElement(i ? "td" : "th") cell.appendChild(input) row.appendChild(cell) }); } document.querySelector('button').onclick = addColumn
 <table id="table"> <tr><th><input type="text" value="test 1" /><th/></tr> <tr><td><input type="text" value="test 2" /><td/></tr> </table> <button type="button">add column</button>

First row will contain a th instead of td . Each new cell contains a input . Feel free to change this to suit your need.

The answer works, but still here is an alternative way where we use thead and tbody !

JS

$('#irow').click(function(){
if($('#row').val()){
    $('#mtable tbody').append($("#mtable tbody tr:last").clone());
    $('#mtable tbody tr:last :checkbox').attr('checked',false);
    $('#mtable tbody tr:last td:first').html($('#row').val());
}
});
$('#icol').click(function(){
if($('#col').val()){
    $('#mtable tr').append($("<td>"));
    $('#mtable thead tr>td:last').html($('#col').val());
    $('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="checkbox">'))});
}
});

Use this code for adding new column:

$('#btnAddCol').click(function () {
    $("tr").append("<td>New Column</td>");
});

But you need to change the value for the first row with a text and others to include a <input type="checkbox" /> . And it is better to

Check it out jsFiddle ............................. http://jsfiddle.net/fmuW6/8/

 $(document).ready(function () {
        $('#btnAdd').click(function () {
              var count = 3, first_row = $('#Row2');
                while(count-- > 0)                    first_row.clone().appendTo('#blacklistgrid');
     });   

        $('#btnAddCol').click(function () {
            $("#blacklistgrid tr").each(function(){
               $(this).append("<td>test</td>");       
            })
     });      
 });

Using a table of 4 columns:

在此处输入图片说明

I can add values dinamically like this:

 var TableId = "table_" + id; 

 var table = $("#" + TableId );

 table.find("tbody tr").remove();
                                            
 table.append("<tr><td>" + "1" + "</td><td>" + "lorem"  + "</td><td>" + "ipsum" + "</td><td>" + "dolor" + "</td></tr>");

and the final result will be:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM