...

View Full Version : random number in to a form field



pouncebounce
08-25-2011, 10:44 AM
hi all, i was hoping somebody could help me out.

i'm trying to write a code that generates a random number between 1 and 9999 on page load, concatenates it with "pwn" at the start, and adds it to a disabled form text input box. this is the code i have below, but it's not working at all. any help would be greatly appreciated.

in the head section

<script type="text/javascript">
function createcode()
{
var randomnumber = Math.floor(Math.random()*10000);
var homecode = 'pwn' + randomnumber;
}
</script>

my body tag

<body onload="createcode()">

and the form field itself

<input type="text" name="homename" id="homename" disabled="disabled" />
<script type="text/javascript">
document.getElementByID("homename").value = homecode;
document.write(homecode);
</script>

thanks in advance.

webdev1958
08-25-2011, 11:14 AM
You're running


document.getElementByID("homename").value = homecode; before createcode() is called (which is not till the body has finished loading) and so homecode hasn't been created yet. And in any case, homecode will have to declared as a global variable so its value can be seen by code outside of createcode().

Variables declared inside a function with the var prefix will be local only to that function. Variables declared inside a function without the var prefix will be global. Variables declared outside a function, with or without the var prefix, will be global.

DaveyErwin
08-25-2011, 12:07 PM
You have getElementByID ,
should be getElementById.
Try like this ...


<script type="text/javascript">
function createcode(){
var randomnumber = Math.floor(Math.random()*10000);
var homecode = 'pwn' + randomnumber;
document.getElementById("homename").value = homecode;
}
</script>


<body onload="createcode()">and the form field itself

<input type="text" name="homename" id="homename" disabled="disabled" />



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum