Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help with a dynamic table script 2

Status
Not open for further replies.

deeciple

Technical User
Mar 1, 2012
70
US
Hi All,

This is my first post and I am fairly new to javascript and web development. I am working on a script to generate a dynamic table and populate the fields in that table with data from a number of text fields on my page.

The page uses Adobe spry validation and this is the only way I can get my validation to function and add the data to the table dynamically (I had a script where the text fields were part of the first row and blank rows were added dynamically but the validation would not work for the added rows... This is a workaround).

Being new to JS I did the best I could and I think it's clear what I am going for but I am sure my syntax and method usage is off. Could someone please help me get going in the right direction with this code? Here it is and thanks in advance for any help.

Code:
A<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>

</style>
<link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />

</head>
		<SCRIPT language="javascript">         
		function addRow(tableID) {
			//These variable are commented out and coded inline below.
			//var StartTime = document.getElementById(StarTime);
			//var EndTime = document.getElementById(EndTime);
			//var MaterialID = document.getElementById(MaterialID);
			//var Title = document.getElementById(Title);               
			
			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";             
			cell1.appendChild(element1);               
			
			var cell2 = row.insertCell(1);             
			var element2 = document.createElement("input");             
			element2.type = "text";
			element2.setAttribute("id","StartTime[]");
			//Set the value to the form's textfield.
			element2.value = document.getElementById(StarTime);             
			cell2.appendChild(element2);              
			
			var cell3 = row.insertCell(2);             
			var element3 = document.createElement("input");             
			element3.type = "text";
			element3.setAttribute("id","EndTime[]");
			//Set the value to the form's textfield.
			element3.value = document.getElementById(EndTime);             
			cell3.appendChild(element3); 

			var cell4 = row.insertCell(3);             
			var element4 = document.createElement("input");             
			element4.type = "text";
			element4.setAttribute("id","MaterialID[]");
			//Set the value to the form's textfield.
			element4.value = document.getElementById(MaterialID);             
			cell4.appendChild(element4);               
			
			var cell5 = row.insertCell(4);             
			var element5 = document.createElement("input");             
			element5.type = "text";
			element5.setAttribute("id","Title[]");
			//Set the value to the form's textfield.
			element5.value = document.getElementById(Title);             
			cell5.appendChild(element5);             
		}           
		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> 
<body>
<span id="spryStartTime">
<label for id="StartTime">Start Time:</label><br />
<input name="StartTime" type="text" id="StartTime" tabindex="1" size="10" maxlength="8" />
<span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br />
<label for id="EndTime">End Time:</label><br />
<span id="spryEndTime">
<input name="EndTime" type="text" id="EndTime" tabindex="2" size="10" maxlength="8" />
<span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br />
<label for id="MaterialID">Material ID:</label><br />
<span id="spryMaterialID">
<input name="MaterialID" type="text" id="MaterialID" tabindex="3" size="10" maxlength="10" />
<span class="textfieldRequiredMsg">A value is required.</span></span><br />
<label for id="Title">Title:</label><br />
<span id="spryTitle">
<input name="Title" type="text" id="Title" tabindex="4" size="50" maxlength="50" />
<span class="textfieldRequiredMsg">A value is required.</span></span><br />
	<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />       
	<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />       
<!--
I would prefer not to start with a table with blank rows
(but rather create the rows already populated)
but I can work on this later.
-->	
	<TABLE id="dataTable" width="350px" border="1">
		<TR>             
			<TD><INPUT type="checkbox" name="chk"/></TD>             
			<TD><INPUT type="text" /></TD>             
			<TD><INPUT type="text" /></TD> 
			<TD><INPUT type="text" /></TD> 
			<TD><INPUT type="text" /></TD>          
		</TR>     
	</TABLE>
<script type="text/javascript" />
var sprytextfield3 = new Spry.Widget.ValidationTextField("spryStartTime", "time", {validateOn:["blur"], format:"HH:mm:ss", useCharacterMasking:true});
var sprytextfield4 = new Spry.Widget.ValidationTextField("spryEndTime", "time", {format:"HH:mm:ss", useCharacterMasking:true, validateOn:["blur"]});
var sprytextfield5 = new Spry.Widget.ValidationTextField("spryMaterialID", "none", {validateOn:["blur"]});
var sprytextfield6 = new Spry.Widget.ValidationTextField("spryTitle", "none", {validateOn:["blur"]});
</script>

</body>
</html>
 
I'm not sure I quite understand what you are doing, however several things in your code are wrong, and would prevent it from correctly running in any way.

[ol]
[li]
Code:
<label for id="StartTime">Start Time:</label><br />
<input name="StartTime" type="text" id="StartTime" tabindex="1" size="10" maxlength="8" />

ID's must be unique. Javascript's getElementById returns the very first object it finds with particular ID since it doesn't expect there will be more. In your case it will return the label before your input element. And since labels have no values you will not be able to set your new elements to the value of the original input. Additionally to this, the for attribute of the label specifies the id of the element its for.

[/li]
[li]
Code:
var element2 = document.createElement("input");             
            element2.type = "text";
            element2.setAttribute("id","StartTime[]");
            //Set the value to the form's textfield.
            element2.value = document.getElementById(StarTime);
You create your new element, but attempt to give it a value that is equal to the input object rather than its value. (as a side note, the ID is neither enquoted as it should be since its a string, nor is it a valid Id that exists in your HTML. Its missing a T Star[red]t[/red]Time)

[/li]

[li]This one stems from point 1. You are giving the same ID to all your newly created elements. I see you are adding [] in an attempt to make them arrays, however this does not work in Javascript, only in the server side language that will process the form, and second it is used with the name attribute not the ID. since the ID never gets sent to the server-side script.

[/li]

[/ol]

A few fixes later:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>

</style>
<link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />

</head>
        <SCRIPT language="javascript">         
        function addRow(tableID) {
            //These variable are commented out and coded inline below.
            //var StartTime = document.getElementById(StarTime);
            //var EndTime = document.getElementById(EndTime);
            //var MaterialID = document.getElementById(MaterialID);
            //var Title = document.getElementById(Title);               
            
            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";             
            cell1.appendChild(element1);               
            
            var cell2 = row.insertCell(1);             
            var element2 = document.createElement("input");             
            element2.type = "text";
            element2.setAttribute("name","StartTime[]");
            //Set the value to the form's textfield.
            element2.value = document.getElementById('StartTime').value;             
            cell2.appendChild(element2);              
            
            var cell3 = row.insertCell(2);             
            var element3 = document.createElement("input");             
            element3.type = "text";
            element3.setAttribute("name","EndTime[]");
            //Set the value to the form's textfield.
            element3.value = document.getElementById('EndTime').value;             
            cell3.appendChild(element3); 

            var cell4 = row.insertCell(3);             
            var element4 = document.createElement("input");             
            element4.type = "text";
            element4.setAttribute("name","MaterialID[]");
            //Set the value to the form's textfield.
            element4.value = document.getElementById('MaterialID').value;            
            cell4.appendChild(element4);               
            
            var cell5 = row.insertCell(4);             
            var element5 = document.createElement("input");             
            element5.type = "text";
            element5.setAttribute("name","Title[]");
            //Set the value to the form's textfield.
            element5.value = document.getElementById('Title').value;             
            cell5.appendChild(element5);             
        }           
        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> 
<body>
<span id="spryStartTime">
<label for="StartTime">Start Time:</label><br />
<input name="StartTime" type="text" id="StartTime" tabindex="1" size="10" maxlength="8" />
<span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br />
<label for="EndTime">End Time:</label><br />
<span id="spryEndTime">
<input name="EndTime" type="text" id="EndTime" tabindex="2" size="10" maxlength="8" />
<span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br />
<label for="MaterialID">Material ID:</label><br />
<span id="spryMaterialID">
<input name="MaterialID" type="text" id="MaterialID" tabindex="3" size="10" maxlength="10" />
<span class="textfieldRequiredMsg">A value is required.</span></span><br />
<label for="Title">Title:</label><br />
<span id="spryTitle">
<input name="Title" type="text" id="Title" tabindex="4" size="50" maxlength="50" />
<span class="textfieldRequiredMsg">A value is required.</span></span><br />
    <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />       
    <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />       
<!--
I would prefer not to start with a table with blank rows
(but rather create the rows already populated)
but I can work on this later.
-->    
    <TABLE id="dataTable" width="350px" border="1">
        <TR>             
            <TD><INPUT type="checkbox" name="chk"/></TD>             
            <TD><INPUT type="text" /></TD>             
            <TD><INPUT type="text" /></TD> 
            <TD><INPUT type="text" /></TD> 
            <TD><INPUT type="text" /></TD>          
        </TR>     
    </TABLE>
<script type="text/javascript" />
var sprytextfield3 = new Spry.Widget.ValidationTextField("spryStartTime", "time", {validateOn:["blur"], format:"HH:mm:ss", useCharacterMasking:true});
var sprytextfield4 = new Spry.Widget.ValidationTextField("spryEndTime", "time", {format:"HH:mm:ss", useCharacterMasking:true, validateOn:["blur"]});
var sprytextfield5 = new Spry.Widget.ValidationTextField("spryMaterialID", "none", {validateOn:["blur"]});
var sprytextfield6 = new Spry.Widget.ValidationTextField("spryTitle", "none", {validateOn:["blur"]});
</script>

</body>
</html>


Now I'm not familiar with how Spry works so can't advise on that, but hopefully this will help you go in the right direction.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Hi Vacunita,

Thank you for all your comments. Now the script works like I had hoped. Being so new to javascript and web developement it's easy to make these errors. But I am learning a great deal and helpful tips like yours are much appreciated!

Best regards,

Ken
 
Glad I could help


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Hi Guys,

Thanks for the help. I was able to get the script to create A table dynamically (instead of starting with an exising table) but I seem to have broken my delete row function. Another strange, although unrelated behavior... I had commented out the variable declarations for "StartTime", "EndTime", "MaterialID" and "Title" and had them coded explicitly when I created my cells. I un-commented them and tried replacing the explicit code with the variable names but this breaks the script altogether.

Thanks in advance for all your help guys!

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>

</style>
<link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />

</head>
        <SCRIPT language="javascript">         
        function addRow(tableID) {
            if (!document.getElementById(tableID)) {
                //alert("the table does not exists");
                 var body = document.getElementsByTagName("body")[0];

                // creates a <table> element and a <tbody> element
                var tbl     = document.createElement("table");
                var tblBody = document.createElement("tbody");
                var row = document.createElement("tr");
                
                // add the row to the end of the table body
                tblBody.appendChild(row);
                
                // put the <tbody> in the <table>
                tbl.appendChild(tblBody);
                
                // appends <table> into <body>
                body.appendChild(tbl);

                // sets the id of "dataTable" and border attribute of tbl to 2;
                tbl.setAttribute("id", "dataTable");
                tbl.setAttribute("border", "0");
                }
            //These variable are commented out and coded inline below.
            //var StartTime = document.getElementById(StarTime);
            //var EndTime = document.getElementById(EndTime);
            //var MaterialID = document.getElementById(MaterialID);
            //var Title = document.getElementById(Title);               
            
            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";             
            cell1.appendChild(element1);               
            
            var cell2 = row.insertCell(1);             
            var element2 = document.createElement("input");             
            element2.type = "text";
            element2.setAttribute("name","StartTime[]");
            //Set the value to the form's textfield.
            element2.value = document.getElementById('StartTime').value;             
            cell2.appendChild(element2);
            document.getElementById('StartTime').value="";              
            
            var cell3 = row.insertCell(2);             
            var element3 = document.createElement("input");             
            element3.type = "text";
            element3.setAttribute("name","EndTime[]");
            //Set the value to the form's textfield.
            element3.value = document.getElementById('EndTime').value;             
            cell3.appendChild(element3);
            document.getElementById('EndTime').value=""; 

            var cell4 = row.insertCell(3);             
            var element4 = document.createElement("input");             
            element4.type = "text";
            element4.setAttribute("name","MaterialID[]");
            //Set the value to the form's textfield.
            element4.value = document.getElementById('MaterialID').value;            
            cell4.appendChild(element4);
            document.getElementById('MaterialID').value="";               
            
            var cell5 = row.insertCell(4);             
            var element5 = document.createElement("input");             
            element5.type = "text";
            element5.setAttribute("name","Title[]");
            //Set the value to the form's textfield.
            element5.value = document.getElementById('Title').value; 
            cell5.appendChild(element5);
            document.getElementById('Title').value="";              
        }           
        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> 
<body>
<span id="spryStartTime">
<label for="StartTime">Start Time:</label><br />
<input name="StartTime" type="text" id="StartTime" tabindex="1" size="10" maxlength="8" />
<span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br />
<label for="EndTime">End Time:</label><br />
<span id="spryEndTime">
<input name="EndTime" type="text" id="EndTime" tabindex="2" size="10" maxlength="8" />
<span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span><br />
<label for="MaterialID">Material ID:</label><br />
<span id="spryMaterialID">
<input name="MaterialID" type="text" id="MaterialID" tabindex="3" size="10" maxlength="10" />
<span class="textfieldRequiredMsg">A value is required.</span></span><br />
<label for="Title">Title:</label><br />
<span id="spryTitle">
<input name="Title" type="text" id="Title" tabindex="4" size="50" maxlength="50" />
<span class="textfieldRequiredMsg">A value is required.</span></span><br />
    <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />       
    <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />       
<script type="text/javascript" />
var sprytextfield3 = new Spry.Widget.ValidationTextField("spryStartTime", "time", {validateOn:["blur"], format:"HH:mm:ss", useCharacterMasking:true});
var sprytextfield4 = new Spry.Widget.ValidationTextField("spryEndTime", "time", {format:"HH:mm:ss", useCharacterMasking:true, validateOn:["blur"]});
var sprytextfield5 = new Spry.Widget.ValidationTextField("spryMaterialID", "none", {validateOn:["blur"]});
var sprytextfield6 = new Spry.Widget.ValidationTextField("spryTitle", "none", {validateOn:["blur"]});
</script>

</body>
</html>
 
I fixed that variable issue (missing quotes). Still need help with the broken Delete Row function.

Thanks,

Ken
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top