Pranav
Pranav

Reputation: 8871

Dynamic Table Row Deletion

I am creating a dynamic table through Javascript. I am taking no. of row and columns from user and creating table. On second time when user enters I am deleting all present rows and creating new rows. Everything is working fine but for deletion when I am using the commented code it is not working while other one is working fine. Can anybody tell me what is the reason behind this?

//deleting preExisting rows:-

for(k=tblObj.rows.length;k>0;k--)
tblObj.deleteRow(k-1);

Above Logic is working fine but below one is not working why???

            /*for(k=0;k<Number(tblObj.rows.length);k++)
                {   
                    tblObj.deleteRow(k);
                }*/   //This Logic is not working:Why???

Upvotes: 0

Views: 194

Answers (2)

Igor Dymov
Igor Dymov

Reputation: 16460

If you are deleting rows from the beginning you have to delete first row rowCount times:

var rowCount = tblObj.rows.length;
for(k=0;k<rowCount;k++)
{   
    tblObj.deleteRow(0);
}

Upvotes: 4

Marco Mariani
Marco Mariani

Reputation: 13766

The tblObj.rows.length value is computed for every loop execution, and the array is getting shorter every time.

Try with

var len = tblObj.rows.length;
for(k=0;k<len;k++)
{   
    tblObj.deleteRow(0);
}

Upvotes: 4

Related Questions