jQuery and tables

I’ve been playing with jQuery the recent weeks, and while it is reasonable simple to get started with and the jQuery documentation is pretty good, I thought I’d share a few snippets of jquery examples/code, which showcases a few simple practical uses for jquery.

First up – tables and jquery.

With jQuery you can add content to a HTML table. Here are to simple examples on how to add content into a table.

First let’s see how you add a row with two cells to a table:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
<table id="tableOne" border="1">
 <thead>
  <tr><th>Col 1 </th><th>Col 2</th></tr>
</thead>
<tbody>
</tbody>
</table>
 
<script type="text/javascript">
$(document).ready(function() {
 
  $tableBody = $('#tableOne tbody');
 
  var $tableRow = $('<tr>');
  $('<td>').text('Row 1 Cell one').appendTo($tableRow);
  $('<td>').text('Row 1 Cell Two').appendTo($tableRow);
  $tableRow.appendTo($tableBody);
 
});
</script>

(se example).

Let’s build a slightly more advanced example and add data to a table from a javascript array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<table id="tableOne" border="1">
 <thead>
  <tr><th>Table Header</th></tr>
</thead>
<tbody>
</tbody>
</table>
 
<script type="text/javascript">
var sampleData = new Array('One', 'Two', 'Three', 'Four');
 
$(document).ready(function() {
  $tableBody = $('#tableOne tbody');
 
  for (var row = 0; row <= sampleData.length-1; row++) {
    var $tableRow = $('<tr>');
    $('<td>').text(sampleData[row]).appendTo($tableRow);
    $tableRow.appendTo($tableBody);
  }
});
</script>

(see example).

Extending the second example and drawing the data populating the table from an ajax-source should be pretty simple. Have fun and enjoy jQuery.