`

Dynamically Add/Remove rows in HTML table using JavaScript

阅读更多

文章源自:http://viralpatel.net/blogs/dynamically-add-remove-rows-in-html-table-using-javascript/

Dynamically Add/Remove rows in HTML table using JavaScript

A good web design involves the better user interaction and ability to fetch the data in a better way. For fetching user data, you may have to create a form wherein user can add multiple entries and submit them simultaneously.

Thus for this you will need a way to add or remove fields dynamically into the HTML page. In my previous article, I had discussed about the way one can add dynamic form components into the web page.

In this article we will create a user interface where user can add/delete multiple rows in a form using JavaScript.

First check the user interface.

In this example, we have created a table which will display our html components. On pressing Add Row, a dynamic row will be created and added in the table. And on selecting the checkbox and pressing Delete Row, the row will be removed.

Following is the source.

<HTML>
<HEAD>
    <TITLE> Add/Remove dynamic rows in HTML table </TITLE>
    <SCRIPT language="javascript">
        function addRow(tableID) {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
 
            var cell1 = row.insertCell(0);
            var element1 = document.createElement("input");
            element1.type = "checkbox";
            element1.name="chkbox[]";
            cell1.appendChild(element1);
 
            var cell2 = row.insertCell(1);
            cell2.innerHTML = rowCount + 1;
 
            var cell3 = row.insertCell(2);
            var element2 = document.createElement("input");
            element2.type = "text";
            element2.name = "txtbox[]";
            cell3.appendChild(element2);
        }
 
        function deleteRow(tableID) {
            try {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
 
            for(var i=0; i<rowCount; i++) {
                var row = table.rows[i];
                var chkbox = row.cells[0].childNodes[0];
                if(null != chkbox && true == chkbox.checked) {
                    table.deleteRow(i);
                    rowCount--;
                    i--;
                }
            }
            }catch(e) {
                alert(e);
            }
        }
    </SCRIPT>
</HEAD>
<BODY>
    <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
    <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
    <TABLE id="dataTable" width="350px" border="1">
        <TR>
            <TD><INPUT type="checkbox" name="chk"/></TD>
            <TD> 1 </TD>
            <TD> <INPUT type="text" /> </TD>
        </TR>
    </TABLE>
</BODY>
</HTML>

 For adding dynamic row in table, we have used insertRow() method. This method will insert a row at position specified by the index arguement. Also for removing row, we have used deleteRow() method.
Note that for inserting dynamic row, we have to created cells by using row.insertCell() method.

 

Add/Remove rows from table having Drop Down List

What if my table has a selectbox or drop down list and I want to implement add/remove row functionality? A lot of people asked me this question (you can check comment section), so I thought to update this article and add one more case. Adding / Removing rows in a table having drop down list.

Following is the code:

<HTML>
<HEAD>
    <TITLE> Add/Remove dynamic rows in HTML table </TITLE>
    <SCRIPT language="javascript">
        function addRow(tableID) {
 
            var table = document.getElementById(tableID);
 
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
 
            var colCount = table.rows[0].cells.length;
 
            for(var i=0; i<colCount; i++) {
 
                var newcell = row.insertCell(i);
 
                newcell.innerHTML = table.rows[0].cells[i].innerHTML;
                //alert(newcell.childNodes);
                switch(newcell.childNodes[0].type) {
                    case "text":
                            newcell.childNodes[0].value = "";
                            break;
                    case "checkbox":
                            newcell.childNodes[0].checked = false;
                            break;
                    case "select-one":
                            newcell.childNodes[0].selectedIndex = 0;
                            break;
                }
            }
        }
 
        function deleteRow(tableID) {
            try {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
 
            for(var i=0; i<rowCount; i++) {
                var row = table.rows[i];
                var chkbox = row.cells[0].childNodes[0];
                if(null != chkbox && true == chkbox.checked) {
                    if(rowCount <= 1) {
                        alert("Cannot delete all the rows.");
                        break;
                    }
                    table.deleteRow(i);
                    rowCount--;
                    i--;
                }
 
 
            }
            }catch(e) {
                alert(e);
            }
        }
 
    </SCRIPT>
</HEAD>
<BODY>
 
    <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
 
    <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
 
    <TABLE id="dataTable" width="350px" border="1">
        <TR>
            <TD><INPUT type="checkbox" name="chk"/></TD>
            <TD><INPUT type="text" name="txt"/></TD>
            <TD>
                <SELECT name="country">
                    <OPTION value="in">India</OPTION>
                    <OPTION value="de">Germany</OPTION>
                    <OPTION value="fr">France</OPTION>
                    <OPTION value="us">United States</OPTION>
                    <OPTION value="ch">Switzerland</OPTION>
                </SELECT>
            </TD>
        </TR>
    </TABLE>
 
</BODY>
</HTML>

 

Check the addRow() method in above code. I have edited this piece of code from our previous example. The addRow() method iterates through all the columns and copy the content of 1st column to new column. This way a new row is created which is exact copy of 1st row. Also the switch{} case in the code make sure that the value are not copied as it is. For example, if you have entered text “abc” in textbox of 1st row and you press Add Row button, the new row will be added and the textbox of this new row will have value “abc”. So to make sure the values are not copied, we have added the switch{} code.

You may want to comment the switch{} code if the copying of the values in newly added row if desired to you.

 

 

分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    Add Textbox Dynamically using jQuery.zip

    "Add Textbox Dynamically using jQuery.zip"这个压缩包中的示例,主要展示了如何利用jQuery在用户交互时动态创建一个新的文本输入框。 首先,jQuery库是一个强大的JavaScript库,它简化了DOM操作、事件处理、动画...

    Android代码-学术实验数据记录APP

    helpEx for Android This project is an Android application for assisting students in recording their Experimental Data, usually for Academic purposes. ...Dynamically add/remove columns. Screenshots

    phpmaker610官方安装版

    Optional list, add/copy, view, edit, delete, multi-update and search pages for each table/view. (See Table Setup) Customizable table display order. Optional Grid-Add, Grid-Edit, Inline-Add, Inline-...

    Beginning JavaScript with DOM Scripting and Ajax: Second Editon

    How build a site that will still work in the case that JavaScript is turned off. How to access and update part of the page using code. How to use JavaScript to communicate with the server and retrieve...

    Beginning JavaScript with DOM Scripting and Ajax (pdf + ePub)

    How build a site that will still work in the case that JavaScript is turned off. How to access and update part of the page using code. How to use JavaScript to communicate with the server and retrieve...

    Spring Dynamic Modules in Action

    With Spring DM, you can easily create highly modular applications and you can dynamically add, remove, and update your modules. Spring Dynamic Modules in Action is a comprehensive tutorial that ...

    JavaScript APIs HTML5

    Basic usage involves embedding `&lt;video&gt;` or `&lt;audio&gt;` tags in your HTML and controlling their behavior using JavaScript. ```html &lt;source src="movie.mp4" type="video/mp4"&gt; ...

    JavaScript in 10 Minutes

    ### JavaScript in 10 Minutes: Key Insights for Intermediate and Advanced Programmers #### Introduction "JavaScript in 10 Minutes" is a concise guide that aims to provide intermediate to advanced ...

    微软内部资料-SQL性能优化5

    Having useful indexes speeds up finding individual rows in a table, as well as finding the matching rows needed to join two tables. What You Will Learn After completing this lesson, you will be able ...

    Dynamically shortened Text with “Show More” link using jQuery

    标题 "Dynamically shortened Text with “Show More” link using jQuery" 涉及的是一个常见的网页交互功能,即使用jQuery库动态地缩短文本并添加“显示更多”链接。这个功能在网页设计中非常常见,特别是在内容...

    cuteEditor6.0

    In either mode tags can be created by using shift+enter.&lt;br/&gt; &lt;br/&gt; 支持代码缩进和小写字母&lt;br/&gt;&lt;br/&gt;Cute Editor displays nicely indented code in the HTML mode and the generating HTML tags and ...

    Windows Presentation Foundation 4.5 Cookbook的源码

    Dynamically sizing grid rows/columns 90 Creating a scrollable user interface 92 Creating a border around panels and elements 94 Placing elements in exact positions 96 Adding/removing elements to ...

    Wave,MP3,Ogg,FLAC转换

    And of course, with ACS you can add sound playing/recording capabilities to any of your applications.ACS is used in QuickPopup sofware as well as in several other projects, including OpenRipper for ...

    WPTools.v6.29.1.Pro

    - workaround for word files which have space characters in table definitions 16.10.2012 - WPTools 6.27'' * some additions to the PRO edition for XE3 26.9.2012 - WPTools 6.27' * The PRO Version now ...

    ABAP Code Sample for ALV Grid from Dynamically Created Internal Table

    在ABAP编程中,ALV Grid(List Viewer)是一种常用的数据展示工具,它可以将数据以表格形式呈现,具有良好的用户界面和交互性。本示例代码展示了如何动态创建内部表,并将其数据填充到ALV Grid中,适用于处理各种...

    Java.EE.and.HTML5.Enterprise.Application.Development

    Dynamically map database objects using Java Persistence API Configure, manage, and invoke RESTful Web Services Maximize messaging efficiency through WebSockets Accept and process ...

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持D4-XE5

    - fixed bug in ODF export with properties table:number-columns-spanned, table:number-rows-spanned - fixed bug in ODF export with the background clNone color - fixed bug in ODF export with a style of ...

    FairyGUI-Unity-Plugin-3.4.0.zip

    * Or using UIPackage.CreateObject to create UI component dynamically, and then use GRoot.inst.AddChild to show it on screen. ----------------- Version History ----------------- 3.4.0 - NEW: Add ...

Global site tag (gtag.js) - Google Analytics