Add/Delete Row In Table Using Javascript

. Thursday, October 18, 2012
  • Agregar a Technorati
  • Agregar a Del.icio.us
  • Agregar a DiggIt!
  • Agregar a Yahoo!
  • Agregar a Google
  • Agregar a Meneame
  • Agregar a Furl
  • Agregar a Reddit
  • Agregar a Magnolia
  • Agregar a Blinklist
  • Agregar a Blogmarks

Hi Guys,Today I will tell you how can you add/delete rows of html table using javascript functions,so lets start with this.
First I m creating a html table very simple table with one row as default to appear.

 
    
Quantity

Now create two buttons which will be used to add/delete row as follows 
 
    
    

What the magic going on here on click of both the buttons ?????
well , when you click on Add Row button javascript function addRowProduct is called which receives the id of table,we've passed inside the single quote, and inside this function we did following :
a) access the table by its id and assign it to var variable.
b) find the total number of rows right now,and insert a empty row to current index which equals to total row count here.
c)create cell at first position i.e. 0 of row and append an element of type input with  its properties like id,type,class name etc inside this cell.

Similarly when clicking on delete button javascript function deleteRow called in which we did following :
a)access the table by its id in var type variable.
b) find the total number of row in table.
c)delete the row of total row count minus 1.

what's the interesting point to remember here is  table row index starts from 0 so while add new row we just need to insert the row with total row count which automatically inserts row to current index and count increases by one while deleting the row we passes the total row count minus 1 because its deletes by index so if total row count is n then we need to delete the row at n-1 index to delete the max. row.
One good news for all my readers now I m on github (a social coding site uses git (distributed version control system)) so that I can share the running code as well for better understanding of how things are happening.
Really amazing isn't it .
Please find the entire code for this stuff here.
Thanks and happy coding... 

0 comments: