Click to See Complete Forum and Search --> : repeat?


IsmAvatar
01-10-2004, 11:33 PM
Sorry to be asking so many questions, but I don't have a javascript book in front of me. If anyone knows a good link to a site that works just as well, please point me to it.
In the meantime, what is the command to repeat a piece of code X many times, where X is a user defined variable?
i know var x = 100 or however to get that working.

Pittimann
01-11-2004, 04:34 AM
Hi!

That depends on what has to be done x times.

Here is an example writing the same line x times (except its'number):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script language="JavaScript" type="text/javascript">
<!--
var writeToDoc;
var minValue=1;//put your min. value here
var maxValue=100;//put your max. value here
function loopIt(){
writeToDoc="";
var usNum=parseInt(document.myForm.usersNumber.value);
if (!isNaN(usNum)&&usNum<=maxValue&&usNum>=minValue){
document.getElementById('resultSpan').innerText="";
for (var x = 1; x <= usNum; x++){
writeToDoc +='This is line # '+ x+'\r\n';
}
document.getElementById('resultSpan').innerText=writeToDoc;
}
else{
alert('Only numbers between '+ minValue + ' and '+maxValue+' allowed!');
return false;
}
}
//-->
</script>
</head>
<body>
<form name="myForm">Please insert a number between
<script language="JavaScript" type="text/javascript">
<!--
document.write(minValue + ' and ' + maxValue + ':');
//-->
</script>
<br>
<input type="text" name="usersNumber"><br>
<input type="button" onClick="loopIt()" value="click me">
</form>
<span id="resultSpan"></span>
</body>
</html>

Cheers - Pit

fredmv
01-11-2004, 07:49 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>untitled</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=iso-8859-1" />
<script type="text/javascript">
//<![CDATA[
function start()
{
var p = document.getElementsByTagName('pre').item(0);
p.firstChild.nodeValue = '';
for(i=0; i<document.forms[0][0].value; i++) p.firstChild.nodeValue += 'This is line ' + i + '\n';
}
//]]>
</script>
</head>
<body>
<form action="#" onsubmit="return start();">
<div>
<label for="max">
Enter number:
</label>
<input type="text" id="max" />
<input type="submit" value="start" />
<pre id="output">&amp;nbsp;</pre>
</div>
</form>
</body>
</html>

IsmAvatar
01-12-2004, 03:04 PM
right, so
repeat:
var x = 2
for(m = 0; m < x; m++) {
}

while:
for(m = 0; m = 0; m = m) {
var m = 1
}

thank you very much.

Nayias
01-12-2004, 04:56 PM
If anyone knows a good link to a site that works just as well

i used: http://www.htmlgoodies.com