Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Aug 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    random number in to a form field

    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
    Code:
    <script type="text/javascript">
    				function createcode()
    				{
    					var randomnumber = Math.floor(Math.random()*10000);
    					var homecode = 'pwn' + randomnumber;
    				}
    			</script>
    my body tag
    Code:
    <body onload="createcode()">
    and the form field itself
    Code:
    <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.

  • #2
    Banned
    Join Date
    Apr 2011
    Posts
    656
    Thanks
    14
    Thanked 69 Times in 69 Posts
    You're running

    Code:
    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.
    Last edited by webdev1958; 08-25-2011 at 11:16 AM.

  • #3
    Regular Coder
    Join Date
    Aug 2010
    Posts
    945
    Thanks
    19
    Thanked 205 Times in 203 Posts
    You have getElementByID ,
    should be getElementById.
    Try like this ...

    Code:
    <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" />


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •