...

View Full Version : Help with a 'for' loop adding form elements



msl27620
03-14-2012, 09:29 AM
I am trying to develop a function that creates a certain number of form elements based on a certain number that a user inputs. It does not do what I want it to do (obviously). The problem lies within the TextBoxAppear() function. The function worked when I tested it by adding just text (document.getElementByID('leftcolumn').innerHTML = "<p>test function</p>" so I know for a fact whatever I added to the function is the problem. What has been added to the function and needs fixing is in BOLD




<!DOCTYPE html>

<html>
<head>
<meta charset = "utf-8">
<title>Exercise 4</title>
<style type = "text/css">
#leftcolumn { width: 300px; border: 1px solid red; float: left}
#rightcolumn { width: 300px; border: 1px solid red; float: left}
</style>

<script>
function start()
{
var button = document.getElementById( "submitButton" );
button.addEventListener( "click", TextBoxAppear, false );
}

function TextBoxAppear()
{

var numberOfValuesInput = document.getElementByID( 'NumberOfValuesField' );
var numberOfValues = parseFloat( numberOfValuesInput.value );
var textBoxCreation = "<form action ="http://www.deitel.com"><p>";
for ( var i = 1; i < numberOfValues; ++i )
{
textBoxCreation += "<label>Value" + i + ":<input id = 'Value" + i + "' type = 'text'></label>";
}
textBoxCreation += "<input id = "calculateButton" type = "button" value = "Calculate"></p></form>
document.getElementById('leftcolumnn').innerHTML = textBoxCreation;
}

window.addEventListener( "load", start, false );

</script>
</head>
<body>
<form action ="http://www.deitel.com">
<p><label>Number of values to be calculated:
<input id = "numberOfValuesField" type = "text"></label>
<input id = "submitButton" type = "button" value = "Submit"></p>
</form>
<div id ="leftcolumn"><p>test left column</p></div>
<div id ="rightcolumn"><p>test right column</p></div>



</body>
</html>

devnull69
03-14-2012, 09:41 AM
Most importantly: The field id is "numberOfValuesField", but you address it with "NumberOfValuesField". Second, and equally important: It's getElementById and not getElementByID. Watch your case.

msl27620
03-14-2012, 09:48 AM
thank you for your help :-). Unfortunately, it still seems to not want to display the form elements at all :-\. I've been trying to watch my case, but it's apparent that I still miss a lot. Any other suggestions?

devnull69
03-14-2012, 10:19 AM
Can you post the full updated code, please?

Anyway, I noticed something else in your original code


var textBoxCreation = "<form action ="http://www.deitel.com"><p>";

If you use the same quote style for inner quotes as for the string delimiter quotes, you need to escape the inner quotes! Otherwise they would be detected as "end of string" delimiters.


var textBoxCreation = "<form action =\"http://www.deitel.com\"><p>";

msl27620
03-14-2012, 10:36 AM
thanks again. here is the updated code:




<!DOCTYPE html>

<html>
<head>
<meta charset = "utf-8">
<title>Exercise 4</title>
<style type = "text/css">
#leftcolumn { width: 300px; border: 1px solid red; float: left}
#rightcolumn { width: 300px; border: 1px solid red; float: left}
</style>

<script>
var numberOfValues = 0;
var arrayOfValues = new Array();
function start()
{
var button = document.getElementById( "submitButton" );
button.addEventListener( "click", TextBoxAppear, false );
}

function TextBoxAppear()
{

var numberOfValuesInput = document.getElementById( 'numberOfValuesField' );
numberOfValues = parseFloat( numberOfValuesInput.value );
var textBoxCreation = "<form action =\"http://www.deitel.com\"><p>";
for ( var i = 1; i < numberOfValues; ++i )
{
textBoxCreation += "<label>Value" + i + ":<input id = 'Value" + i + "' type = 'text'></label>";
}
textBoxCreation += "<input id = "calculateButton" type = "button" value = "Calculate"></p></form>
document.getElementById('leftcolumnn').innerHTML = textBoxCreation;
}




window.addEventListener( "load", start, false );

</script>
</head>
<body>
<form action ="http://www.deitel.com">
<p><label>Number of values to be calculated:
<input id = "numberOfValuesField" type = "text"></label>
<input id = "submitButton" type = "button" value = "Submit"></p>
</form>
<div id ="leftcolumn"><p>test left column</p></div>
<div id ="rightcolumn"><p>test right column</p></div>



</body>
</html>


I'm definitely going to be up all night. After I fix that function, I have to allow the user to input values into those textboxes, add each value into an array, sort the array in ascending order, refresh the textboxes to show that they are in ascending order, then display the mean, variance and standard deviation. I would just like this function fixed, because I wont be able to test the following code without the TextBoxAppear() function working properly. That's the life of learning Javascript for the first time I guess hehe.

devnull69
03-14-2012, 10:44 AM
Only one more finding


textBoxCreation += "<input id = "calculateButton" type = "button" value = "Calculate"></p></form>

this line has the same issue of inner/outer quote style as in my previous post, plus it's missing the closing quote character.

To help you get some sleep: You definitely need to start to learn how to debug. It will certainly give you some more hours for sleeping :-) If you use Firefox, try the Firebug plug-in (and get used to it!!). In IE, Chrome and Opera there are built-in developer tools.

Those tools would have shown you all of the previously mentioned issues before you needed to ask questions here.

msl27620
03-14-2012, 10:52 AM
Fixed those mistakes ... still no solution. I wish there was a program that I could use to write Javascript that makes it easier to catch errors like VB has ... oh well I guess practice makes perfect. Here is the updated code:



<!DOCTYPE html>

<html>
<head>
<meta charset = "utf-8">
<title>Exercise 4</title>
<style type = "text/css">
#leftcolumn { width: 300px; border: 1px solid red; float: left}
#rightcolumn { width: 300px; border: 1px solid red; float: left}
</style>

<script>
var numberOfValues = 0;
var arrayOfValues = new Array();
function start()
{
var button = document.getElementById( "submitButton" );
button.addEventListener( "click", TextBoxAppear, false );
}

function TextBoxAppear()
{

var numberOfValuesInput = document.getElementById( 'numberOfValuesField' );
numberOfValues = parseFloat( numberOfValuesInput.value );
var textBoxCreation = "<form action ='http://www.deitel.com'><p>";
for ( var i = 1; i < numberOfValues; ++i )
{
textBoxCreation += "<label>Value" + i + ":<input id = 'Value" + i + "' type = 'text'></label>";
}
textBoxCreation += "<input id = 'calculateButton' type = 'button' value = 'Calculate'></p></form>"
document.getElementById('leftcolumnn').innerHTML = textBoxCreation;
}




window.addEventListener( "load", start, false );

</script>
</head>
<body>
<form action ="http://www.deitel.com">
<p><label>Number of values to be calculated:
<input id = "numberOfValuesField" type = "text"></label>
<input id = "submitButton" type = "button" value = "Submit"></p>
</form>
<div id ="leftcolumn"><p>test left column</p></div>
<div id ="rightcolumn"><p>test right column</p></div>



</body>
</html>

devnull69
03-14-2012, 11:04 AM
See my comment about "debugging" in my previous post!

The following error wouldn't have escaped you:


document.getElementById('leftcolumnn').innerHTML = textBoxCreation;

It's 'leftcolumn' with only one "n"

If you want to have 3 elements if you enter "3" you need to change the for loop to


for ( var i = 1; i <= numberOfValues; ++i )

msl27620
03-14-2012, 11:11 AM
awesome! it worked. Thank you very much. A little more on debugging. I am using Google Chrome and when I view page source, how am I supposed to catch the errors like you have mentioned? I am new to Javascript (very obvious) and there seem to be a lot of tools when it comes to Inspect element and none of them seemed to easily show me those mistakes.

Also do you know if it is possble to add a number to i in a for loop in the middle of describing which element you are retrieving by ID? for example:



for ( i=0; i < numberOfValues; ++i )
{
arrayOfValues[i] = parseFloat( document.getElementById( "'Value'+(i + 1)").value );
}


could something like that work?

devnull69
03-14-2012, 11:15 AM
If your id attributes are like value1, value2 etc. you can do this


document.getElementById('value'+i)


In Chrome it's

Toolbox / Tools / Developer Tools ... or Ctrl-Shift-I or just F12

If you click on the "Console" tab of the tools, you'll see all the syntax errors or exceptions (or everything else you want to show there ... maybe using console.log() in your code). There are plenty of good tutorials all over the net, I prefer to learn via screencasts (www.youtube.com, www.screenr.com etc.)

msl27620
03-14-2012, 11:25 AM
they are, but the problem is whenever I named them, they were named with a for loop starting with i = 1 for display purposes:



for ( var i = 1; i <= numberOfValues; ++i )
{
textBoxCreation += "<label>Value " + i + ":<input id = 'Value" + i + "' type = 'text'></label><br>";
}


but when it comes to getting their values and storing them in an array, I started the loop with i = 0



for ( i=0; i <= numberOfValues; ++i )
{
arrayOfValues[i] = parseFloat( document.getElementById( "'Value'+(i + 1)").value );
}


do you think it would be easier to declare a variable in the function that would equal i + 1, so maybe something like this:

EDIT:


function CalculateStatistics()
{
variableIPlusOne = 0
for ( i=0; i <= numberOfValues; ++i )
{
variableIPlusOne = 1 + i
arrayOfValues[i] = parseFloat( document.getElementById( "Value"+variableIPlusOne).value );
}
arrayOfValues.sort(function(a,b){return a - b})
}


sorry for asking so many questions, you can stop answering them when you want. I'm just a helpless newbie at the moment. I have some background in other programming languages, just none as sensitive as Javascript. I'm not used to the Syntax quite yet either. I've been thanking you for your generous and very helpful answers though.

devnull69
03-14-2012, 11:41 AM
No need for an extra variable

1. You should get used to running loops from 0 to length-1 ... this is the usual way
2. If you want to access (i+1) for e.g. getElementById inside the loop, you can easily do this


document.getElementById('Value'+(i+1))

msl27620
03-14-2012, 12:29 PM
I went ahead and did that. I'm getting another error: cannot set property 'value' of null. I know what that means, but I don't know why it's trying to send a null value. With the code that I have it should be assigning the values of the text boxes to the array, sorting them, and then repopulating the textboxes in the proper order. This is what I have for the function:



function CalculateStatistics()
{

for ( i=0; i < numberOfValues; ++i )
{
arrayOfValues[i] = parseFloat( document.getElementById( "Value"+(i+1)).value );
}
arrayOfValues.sort(function(a,b){return a - b});
var arrayLength = arrayOfValues.length;

for ( i=0; i< arrayLength; ++i )
{

document.getElementById("value"+(i+1)).value = arrayOfValues[i];
}

msl27620
03-14-2012, 01:30 PM
Thank you very much devnull69 for all of your help. Through your tips and troubleshooting help, I was able to complete this webpage. It doesn't seem like much to some people, but with only 2 weeks of javascript experience, it was like pulling teeth for me. Here is the completed Web Page that calculates the mean, variance, and standard deviation for a specified set of numbers if anyone is interested in looking at it:




<!DOCTYPE html>

<html>
<head>
<meta charset = "utf-8">
<title>Exercise 4</title>
<style type = "text/css">
#leftcolumn { width: 300px; border: 1px solid red; float: left}
#rightcolumn { width: 400px; border: 1px solid red; float: left}
</style>

<script>
var numberOfValues = 0;
var arrayOfValues = new Array();
var length = 0;
var Sum = 0;
var average = 0;
var squared = 0;
var STD = 0;
var variance = 0;
function start()
{
var button = document.getElementById( "submitButton" );
button.addEventListener( "click", TextBoxAppear, false );
}

function TextBoxAppear()
{

var numberOfValuesInput = document.getElementById( 'numberOfValuesField' );
numberOfValues = parseFloat( numberOfValuesInput.value );
var textBoxCreation = "<form action ='http://www.deitel.com'><p>";
for ( var i = 1; i <= numberOfValues; ++i )
{
textBoxCreation += "<label>Value " + i + ":<input id = 'Value" + i + "' type = 'text'></label><br>";
}
textBoxCreation += "<input id = 'calculateButton' type = 'button' value = 'Calculate'></p></form>";
document.getElementById("leftcolumn").innerHTML = textBoxCreation;
document.getElementById( "calculateButton" ).addEventListener("click", CalculateStatistics, false);
}

function CalculateStatistics()
{

for ( i=0; i < numberOfValues; ++i )
{
arrayOfValues[i] = parseFloat( document.getElementById( "Value"+(i+1)).value );
}
arrayOfValues.sort(function(a,b){return a - b});

length = arrayOfValues.length;

var arrayListed = "<p>Numbers Calculated: </p><br>"


for ( i=0; i< length; ++i )
{
Sum += arrayOfValues[i];
arrayListed += "Value " + (i+1) + ": " + arrayOfValues[i] + "<br>";
}
document.getElementById("leftcolumn").innerHTML = arrayListed;
average = Sum/length;

for ( i=0; i< length; ++i )
{
squared += (arrayOfValues[i] - average)*(arrayOfValues[i]-average);
}
variance = squared/length;
STD = Math.sqrt(variance);
resultsCreation = "<p>The Number of Values Calculated: " + length + "<br>The Average of the numbers is: " + average + "<br>The Variance of the numbers is: " + variance + "<br>The Standard Deviation of the numbers is: " + STD + "</p>";
document.getElementById("rightcolumn").innerHTML = resultsCreation;
}



window.addEventListener( "load", start, false );

</script>
</head>
<body>
<form action ="http://www.deitel.com">
<p><label>Number of values to be calculated:
<input id = "numberOfValuesField" type = "text"></label>
<input id = "submitButton" type = "button" value = "Submit"></p>
</form>
<div id ="leftcolumn"><p>test left column</p></div>
<div id ="rightcolumn"><p>test right column</p></div>



</body>
</html>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum