Skip To Main Content | Home | Sitemap | Contact
Latest Visitors: United States's flagUnited States's flagUnited States's flagUnited States's flagUnited States's flagUnited States's flagNetherlands's flagChina's flagSweden's flagSerbia's flagChina's flagChina's flagUnited States's flagCanada's flagUnited States's flagUnited Kingdom's flagKorea  Republic of's flagUnited States's flagUnited States's flagChina's flagUnited Kingdom's flagUnited States's flagEurope's flagChina's flagSweden's flag
 

How can you dynamically add rows and fields to a table?

Using the DOM methods "createElement" and "appendChild(newElement)" we can add any element to an existing page's DOM.  In the JavaScript function "insertRow()" we first locate the table element, find it's number of existing rows, create the various row, cell, and input elements which go into the new row and then append the new row element to the table.

NOTE: The page uses the

The purpose of course is to avoid XSS, SQL Injection, and CSRF in this page. The added benefit is you write less new code and have robust error handling using the libraries.

Header
  



<!--METADATA TYPE="typelib" uuid="00000205-0000-0010-8000-00AA006D2EA4" -->
<%
Option Explicit
Session.CodePage=65001
Response.Charset="UTF-8"
%>
<!--#include virtual="include/base64.asp"-->
<!--#include virtual="include/hashSHA1.asp"-->
<!--#include virtual="include/form_token.asp"-->
<!--#include virtual="include/generalPurpose.asp"-->
<!--#include virtual="include/paramSQL.asp"-->
<%
Dim cmdTxt, htmlOut

cmdTxt = "SELECT code, description FROM states;"
openCommand Application("examples"),"getStates 1"
getRS db_rs, cmdTxt, "getStates 2"
If Not(db_rs.bof AND db_rs.eof) Then
    Dim tmpStr
    tmpStr = "<scr" & "ipt type=" & chr(34) & "text/javascr" & "ipt" & chr(34) & ">" & vbLF

    ' declare a client side array
    tmpStr = tmpStr & " var csArray=new Array();" & vbLF & vbLF

    Dim idx, item
    idx = 0 ' JavaSccript arrays are zero based.

    ' fill the array from our recordset
    While NOT db_rs.eof
        tmpStr = tmpStr & " csArray["& idx &"]=(['"
        for each item in db_rs.fields
            tmpStr = tmpStr & item & "','"
        next

        ' backoff the trailing ,' and terminate the line with ]);
        tmpStr = Left(tmpStr, Len(tmpStr)-2) & "]);" & vbLF

        ' increment our array index
        idx = idx + 1
        db_rs.movenext
    Wend

    tmpStr = tmpStr & "</scr" & "ipt>" & vbLF
End If

closeRS
closeCommand

Dim posted, numRows
posted = ""
if request.servervariables("HTTP_METHOD")="POST" then
    checkToken
    if CInt(request.form("numRows")) >= 0 then
        numRows = CInt(request.form("numRows"))
        for idx=0 to numRows
            if request.form("cb"&idx) = "" then
                posted = posted & "Row " & idx & " Not Checked "
            else
                posted = posted & "Row " & idx & " Checked "
            end if
            if request.form("sel"&idx) = "" then
                posted = posted & " Value=Empty<br>"
            else
                posted = posted & " Value=" & request.form("sel"&idx) & "<br>"
            end if 
        next
    end if 
end if
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="Roderick Divilbiss">
<meta name="copyright" content="© 2005-2010 Roderick Divilbiss">
<title>Adding Dynamic Rows To A Table After Page Load</title>
<% Response.Write tmpStr %>
<script type="text/javascript">
var numberOfRows = 0;

function insertRow(tblId) {
    var tbl = document.getElementById(tblId);
    var iteration = tbl.tBodies[0].rows.length;
    newRow = tbl.tBodies[0].insertRow(-1);
    var newCell = newRow.insertCell(0);
    var newCell1 = newRow.insertCell(1);
    var el = document.createElement('input');
    el.type = 'checkbox';
    el.name = 'cb' + iteration;
    el.id = 'cb' + iteration;
    newCell1.appendChild(el);

    var newCell2 = newRow.insertCell(1);
    var newCell1 = newRow.insertCell(1);
    var sel = document.createElement('select');
    sel.name = 'sel' + iteration;
    sel.id = 'sel' + iteration;

    for (var idx=0;idx<csArray.length;idx++) {
        sel.options[idx] = new Option(csArray[idx][0], csArray[idx][1]); 
    }
    newCell2.appendChild(sel);
    document.getElementById('numRows').value=iteration;
}

function deleteAllRows(tblId) {
    var tbl = document.getElementById(tblId);
    for (var i=tbl.tBodies[0].rows.length-1; i>=0; i--) {
        tbl.tBodies[0].deleteRow(i);
    }
}
</script>
</head>
<body>
<noscript><p>You need JavaScript to view this example.</p></noscript>
<div><%=posted%></div>
<form action="<%="http://" & Request.ServerVariables("SERVER_NAME") & Request.ServerVariables("SCRIPT_NAME")%>" method="post">
<p><input value="Add" onclick="insertRow('tblInsertRow');" type="button">
<input value="Reset" onclick="deleteAllRows('tblInsertRow');" type="button">
<input value="Submit" type="submit"><%writeToken%></p>
<table id="tblInsertRow" border="0" cellspacing="0">
  <thead>
    <tr>
      <th colspan="2">Header</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td><select id="sel0" name="sel0"><option value="Alaska">AK</option><option value="Alabama">AL</option><option value="Arkansas">AR</option><option value="Arizona">AZ</option><option value="California">CA</option><option value="Colorado">CO</option><option value="Connecticut">CT</option><option value="District Of Columbia">DC</option><option value="Delaware">DE</option><option value="Florida">FL</option><option value="Georgia">GA</option><option value="Hawaii">HI</option><option value="Iowa">IA</option><option value="Idaho">ID</option><option value="Illinois">IL</option><option value="Indiana">IN</option><option value="Kansas">KS</option><option value="Kentucky">KY</option><option value="Louisiana">LA</option><option value="Massachusetts">MA</option><option value="Maryland">MD</option><option value="Maine">ME</option><option value="Michigan">MI</option><option value="Minnesota">MN</option><option value="Missouri">MO</option><option value="Mississippi">MS</option><option value="Montana">MT</option><option value="North Carolina">NC</option><option value="North Dakota">ND</option><option value="Nebraska">NE</option><option value="New Hampshire">NH</option><option value="New Jersey">NJ</option><option value="New Mexico">NM</option><option value="Nevada">NV</option><option value="New York">NY</option><option value="Ohio">OH</option><option value="Oklahoma">OK</option><option value="Oregon">OR</option><option value="Pennsylvania">PA</option><option value="Puerto Rico">PR</option><option value="Rhode Island">RI</option><option value="South Carolina">SC</option><option value="South Dakota">SD</option><option value="Tennessee">TN</option><option value="Texas">TX</option><option value="Utah">UT</option><option value="Virginia">VA</option><option value="Virgin Islands">VI</option><option value="Vermont">VT</option><option value="Washington">WA</option><option value="Wisconsin">WI</option><option value="West Virginia">WV</option><option value="Wyoming">WY</option></select></td>
      <td><input id="cb0" name="cb0" type="checkbox"></td>
    </tr>
  </tbody>
</table>
<p><input id="numRows" name="numRows" type="hidden" value="0"></p>
</form>
</div>
</body>

</html>


This Weeks Most Popular Pages Newest Pages