Reputation: 2824
I have built very simple dynamic html table generator using jquery, check following...
<button id="addcolumn">Add Column</button>
<button id="addrow">Add Row</button>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<thead id="theads">
<tr>
<th class="th" contenteditable>Heading</th>
<th class="th" contenteditable>Heading</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
jquery
$(document).ready(function () {
//add head
$('#addcolumn').click(function(){
$('<th class="th" contenteditable>Heading</th>').appendTo('thead tr');
});
//add row
$('#addrow').click(function(){
var totalths = $('.th').length;
var trcon = '<tr>';
for (var i = 0; i < totalths; i++) {
var trcon = trcon + ' <td class="td" align="center" contenteditable>Content</td>';
}
var trcon = trcon + ' </tr>';
$(trcon).appendTo('tbody');
});
});
This currently add th
on clicking Add Column button and add rows on clicking add row button with td = calculated numbers of th
, its working fine, but i am facing a problem, suppose i add 3 columns and 2 rows with 3 tds, but if i want to add more columns after creating 2 rows, it doesn't increase tds in those rows. I hope you understand my problem. thanks. try this in jsfiddle as well.
Upvotes: 0
Views: 4384
Reputation: 298076
You could do something like this:
$(document).ready(function () {
var $cell = $('<td>', {
'class': 'td',
'align': 'center',
'contenteditable': '',
'text': 'Content'
});
var $header = $('<th>', {
'class': 'th',
'contenteditable': '',
'text': 'Heading'
});
$('#addcolumn').click(function() {
$header.clone().appendTo('thead tr');
$cell.clone().appendTo('tbody tr');
});
$('#addrow').click(function(){
var $row = $('<tr>');
$('thead th').each(function() {
$cell.clone().appendTo($row);
});
$row.appendTo('tbody');
});
});
Demo: http://jsfiddle.net/prBZS/4/
Upvotes: 3
Reputation: 700172
In the event handler for the column adding button, just add a cell to the already existing rows:
//add head
$('#addcolumn').click(function(){
$('<th class="th" contenteditable>Heading</th>').appendTo('thead tr');
$('<td class="td" align="center" contenteditable>Content</td>').appendTo('tbody tr');
});
Upvotes: 1