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:

  

Col 1 

Col 2

 

<script type="text/javascript">
$(document).ready(function() {
<div></div>
  $tableBody = $('#tableOne tbody');
<div></div>
  var $tableRow = $('<tr>');
  $('<td>').text('Row 1 Cell one').appendTo($tableRow);
  $('<td>').text('Row 1 Cell Two').appendTo($tableRow);
  $tableRow.appendTo($tableBody);
<div></div>
});
</script>

 

(se example).

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

  

Table Header

 

<script type="text/javascript">
var sampleData = new Array('One', 'Two', 'Three', 'Four');
<div></div>
$(document).ready(function() {
  $tableBody = $('#tableOne tbody');
<div></div>
  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.