Saturday, January 26, 2013

Creating Dynamic Tables with jQuery

I have been doing some search on a decent tutorial on how you can create and modify dynamic tables with jQuery but I was not so lucky, and I thought about writing one, myself. Let's get to it, then! 

Example Scenario:

In this example, we would like to insert a passenger's name and gender inside a list. The list will be dynamically created, of course.

1. Create the table's empty layout:

While you do not have to create your table per se, but a table layout is needed. Take a look at one way you can do this:

Passengers' List
ID Name Gender Row Operation
Also we would need to enter the passenger's name and gender. We do so by declaring an input textbox and drop-down list. Note that a button is supposed to fire up the event to insert the values in the dynamic table:
Enter passenger's name: 
  Enter passenger's gender: 
  


  

2. Add rows to dynamic table:

First step is to handle the click function of the Add Passenger button.
$('#add-new-passenger').click(function(){
  var passGender = $('#new-passenger-gender').val();
  var passName = $('#new-passenger-name').val();

   counter++;
   var row = $('table.passenger-list').find('.passenger').clone();
   row.attr("class", "")
   row.find('.rowId').html(fcounter);
   row.find('.rowName').html(passName);
   row.find('.rowGender').html(passGender);
   row.find('.rowLink a.delete').html('Delete');
   $('table.passenger-list').find('tbody').append(row);
 });


The challenge here is that we used the clone() function of jQuery to copy the layout of the first row, then we used the find() function to retrieve a row and then set the html attribute of each row according to the dynamic table layout of ours. Then one can select the table and finally appended the row to the table.


3. Delete rows from dynamic table:

This part somehow needs the smallest peace of code and at the same time can be a little bit tricky for some guys. What I encourage people to avoid using the old depreciated live() function, and as jQuery recommended use on('click', '', ) instead:

$('table.passenger-list').on('click',  'a.delete', function() {
  $(this).parents("tr").remove();
 });

As you can see, after handling the click event of the link within delete class, we select the parent row and perform deletion.

No comments:

Post a Comment