PDA

View Full Version : Using for() in a function


Riboflavin
02-26-2005, 12:42 AM
I am very new to JS and I was just playing around trying to make a random number generator.

I was using for() to make it be 10 digits long and it works when I had it in the <script> tags alone but when I tried to make it a function actvated by the button it seemed to only come out with 1 digit.

Thanks in Advance for the help,
Ribo


<html>
<head>
<title>JAVAWHAT?</title>
<script>
function rand()
{
for (count = 0; count<10; count++)
document.write(Math.round(Math.random()*10))
}

</script>
</head>
<body>
<br>
<input type="button" value="Generate" onClick = "rand()">
</body>
</html>

liorean
02-26-2005, 12:47 AM
document.write only works while the document is still being loaded. If the document has finished loading, it will open a new document to write to, and replace the current document with that one.

Riboflavin
02-26-2005, 12:53 AM
I see, what should I use instead?

liorean
02-26-2005, 01:25 AM
Give some element an id, and then use something like this:document.getElementById(id).innerHTML+=
Math.floor(Math.random()*10);

Riboflavin
02-26-2005, 10:32 PM
Ok I changed it around but its still only showing 1 digit


<html>
<head>
<title>JAVAWHAT?</title>
<script>
function rand()
{
for (count = 0; count<10; count++)
document.form.password.value=Math.round(Math.random()*9)
}

</script>
</head>
<body>
<form name="form">
<br>
<input type="button" value="Generate" onClick = "rand()">
<br>
<input type="text" name = "password" value="Your Password Is...">
</form>
</body>
</html>


:confused:

liorean
02-27-2005, 12:38 AM
You're overwriting the previous value each time through the loop.

Riboflavin
02-27-2005, 12:48 AM
Is there a better way to get it to display multiple digits. I was very confused by your earlier post.