Web Analytics Made Easy -
StatCounter random number in to a form field - CodingForum

Announcement

Collapse
No announcement yet.

random number in to a form field

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new 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
    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; Aug 25, 2011, 07:16 AM.

    Comment


    • #3
      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" />

      Comment

      Working...
      X