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:
ID | Name | Gender | Row Operation |
---|---|---|---|
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.
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