Using jQuery - Add row to table

During this days some people ask me about creating dynamic data entry ui . I try to explain it with a real Example step by step .

First Draw an HTML Table with two rows , header and a row with text boxes for data Entry .


Remember that last textbox in the second row must have a lastElement css class.
The simplest way for add a new row to a table is .append() method , but in this approach you should know the new row structure .Using .clone() method make it more easy and flexible. Now the only thing to do is getting the last row of table and call .clone() method on it.

The clone method gets an optional Boolean parameter to clone selected DOM elements with all event handlers or not .

OK , you got cloned element and now you should insert it at the end of the table using .insertAfter() method.



put this line of code to a function and call it on press enter on last text box of each row.
you should handle keypress event of last input that has lastElement class.



The condition "e.which == 13" checks if pressed key is Enter or not.
Test your code ... yes it works , but a little problem , if you enter some data in text boxes clone() method copy text boxes with their values and its not good . select the new added row (now is a last row in table) and select all inputs and clear their values .


Another point is focus must be set to first text box of new row , do it ...



I try to keep this post simple , but if you know how to do ajax save , you can add a method to save last row before add new row in UI .

and here is the completed code ...

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites