Skip to content

Instantly share code, notes, and snippets.

@stevefrost
Created January 13, 2012 14:05
Show Gist options
  • Save stevefrost/1606369 to your computer and use it in GitHub Desktop.
Save stevefrost/1606369 to your computer and use it in GitHub Desktop.
Expandable table
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Expandable Table</title>
<style>
table, th, td {
border: 1px solid #000;
text-align: center;}
</style>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#add_row').click(function(event) { // add rows to table
event.preventDefault();
var thead = $('#table thead');
var tbody = $('#table tbody');
var cols = $('#table thead tr').children().size();
var rows = $('#table tbody').children().size();
var tds = '';
//create a new table row
for(i = 1; i < cols; i++) {
tds = tds + '<td>Column ' + i + '<br>Row ' + (rows + 1) + '</td>';
}
//append to table
$('<tr><th>Row ' + (rows + 1) + '</th>' + tds + '</tr>').appendTo('#table tbody').hide().fadeIn('slow');
});
$('#add_col').click(function(event) { // add columns to table
event.preventDefault();
var thead = $('#table thead');
var tbody = $('#table tbody');
var cols = $('#table thead tr').children().size();
var rows = 1;
// append new thead row
$('<th>Column ' + (cols) + '</th>').appendTo($('#table thead > tr')).hide().fadeIn('slow');
// append new table division to each row
$('#table tbody > tr').each(function() {
$('<td>Column ' + cols + '<br>Row ' + rows + '</td>').appendTo($(this)).hide().fadeIn('slow');
rows++;
});
});
$('#del_row').click(function(event) {
event.preventDefault();
var tbody = $('#table tbody');
$('#table tbody tr:last-child').fadeOut('slow', function() {
$(this).remove();
});
});
$('#del_col').click(function(event) {
event.preventDefault();
$('#table thead tr th:last-child').fadeOut('slow', function() {
$(this).remove()
});
$('#table tbody tr td:last-child').each(function() {
$(this).fadeOut('slow', function() {
$(this).remove()
});
});
});
});
</script>
</head>
<body>
<button id="add_row">Add Row</button>
<button id="add_col">Add Column</button>
<button id="del_row">Delete Row</button>
<button id="del_col">Delete Column</button>
<table id="table">
<thead>
<tr>
<th></th>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</thead>
<tbody>
<tr>
<th>Row 1</th>
<td>Column 1<br>Row 1</td>
<td>Column 2<br>Row 1</td>
<td>Column 3<br>Row 1</td>
</tr>
<tr>
<th>Row 2</th>
<td>Column 1<br>Row 2</td>
<td>Column 2<br>Row 2</td>
<td>Column 3<br>Row 2</td>
</tr>
</tbody>
</table>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment