Dynamically add and delete table rows using JS

Source: Internet
Author: User

 

// Dynamically Add rows

Function addrow (){
VaR table = Document. getelementbyid ("tableid ");
VaR newrow = table. insertrow (); // create a new row
VaR newcell1 = newrow. insertcell (); // create a new cell
Newcell. innerhtml = ""; // content in the cell
Newcell. setattribute ("align", "center"); // set the location
} // Dynamically Delete row function deleterow (){
VaR rowindex = event. srcelement. parentelement. parentelement. rowindex;
VaR styles = Document. getelementbyid ("tableid ");
Styles. deleterow (rowindex );
}

<HTML>

<Head>

<Title> </title>

</Head>

<Body>
<Table id = "testtbl" border = 1>
<Tr>
<TD>
Product Name
</TD>
<TD>
Product Quantity
</TD>
<TD>
Unit Price
</TD>
</Tr>
<Tr>
<TD>
<Select name = "A">
<Option value = "electronics"> electronics </option>
<Option value = "electrical appliance"> electrical appliance </option>
</SELECT> </TD>
<TD>
<Input type = "text" name = "B">
</TD>
<TD>
<Input type = "text" name = "C">
</TD>
</TD>
</Table>

<Input type = "button" name = "submit2" value = "add" onclick = "addrow ()">

<SCRIPT>
Function addrow (){

// Add rows

VaR newtr = testtbl. insertrow ();

// Add a column

VaR newtd0 = newtr. insertcell ();

VaR newtd1 = newtr. insertcell ();

VaR newtd2 = newtr. insertcell ();

VaR newtd3 = newtr. insertcell ();

// Set the column content and attributes

Newtd0.innertext = Document. All ("A"). Options [document. All ("A"). selectedindex]. text;

Newtd1.innertext = Document. All ("B"). value;

Newtd2.innertext = Document. All ("C"). value;

Newtd3.innerhtml = '<input type = "button" name = "Del" value = "delete" onclick = "del (this)"> ';

}
Function del (o)
{
VaR T = Document. getelementbyid ('testtbl ');
T. deleterow (O. parentnode. parentnode. rowindex)
}
</SCRIPT>

</Body>

</Html>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.