Adding or deleting table rows using JavaScript

Source: Internet
Author: User

The following is the HTML for adding table rows. You can click Add to add a row. For example, it is very useful to add table rows without refreshing the parent window when adding a pop-up form.

<Script language = JavaScript>
Function addrow (){

// Add a row

VaR newtr = testtbl. insertrow ();

// Add two columns

VaR newtd0 = newtr. insertcell ();

VaR newtd1 = newtr. insertcell ();

// Set the column content and attributes

Newtd0.innerhtml = '<input type = checkbox id = "box4"> ';

Newtd1.innertext = 'new line ';

}
</SCRIPT>
<Table id = "testtbl" border = 1>

<Tr id = "tr1">

<TD width = 6%> <input type = checkbox id = "box1"> </TD>

<TD id = "B"> first line </TD>

</Tr>

<Tr id = "tr2">

<TD width = 6%> <input type = checkbox id = "box2"> </TD>

<TD id = "B"> Row 2 </TD>

</Tr>

<Tr bgcolor = # 0000ff>

<TD width = 6%> <input type = checkbox id = "box3"> </TD>

<TD> Row 3 </TD>

</Tr>

</Table>
<Input type = button onclick = "addrow ()">

The following is the HTML for deleting table rows:

<HTML>

<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Title> </title>
</Head>

<Body>
<Table id = "TBL" border = 1 width = "100%">
<Tr>
<TD> <input id = chk type = checkbox> 1 </TD> <TD> content </TD>
</Tr>
<Tr>
<TD> <input type = checkbox> 2 </TD> <TD> content </TD>
</Tr>
<Tr>
<TD> <input type = checkbox> 3 </TD> <TD> content </TD>
</Tr>
<Tr>
<TD> <input type = checkbox> 4 </TD> <TD> content </TD>
</Tr>
</Table>
<Input type = button onclick = "deltblrows ()" value = "delete">
</Body>

<Script language = JavaScript>
Function deltblrows (){
 
For (VAR I = 0; I <TBL. Rows. length; I ++ ){
/*
"TBL. Rows (I). getelementsbytagname (" input ") (0)" is used to obtain the first input tag of a row. In this example, checkbox is used as the first input tag.
*/

If (TBL. Rows (I). getelementsbytagname ("input") (0). Checked ){
TBL. deleterow (I );
I --;
}
}
}
</SCRIPT>

</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.