Javascript random number generator for hidden field

I have a script that generates a random number:

<script>
now = new Date();
randomNum = '';
randomNum += Math.round(Math.random()*9);
randomNum += Math.round(Math.random()*9);
randomNum += now.getTime();

var elem = document.getElementById("ID_UNIQUE");
elem.value = randomNum;
</script>

      

And I'm trying to pass "ID_UNIQUE" to a hidden form field:

<form method="POST" action="action.php" name="form" onSubmit="return checkFields();">
<input type="hidden" name="ID_UNIQUE" onsubmit="this.ID_UNIQUE.value=randomNum">

      

Unfortunately, this won't work. When the form is submitted, the value is blank. Thoughts?

Any help is appreciated

+3


source to share


1 answer


There is no onsubmit

for input fields, so it this.ID_UNIQUE.value=randomNum

never starts.

Also, regarding the following code

var elem = document.getElementById("ID_UNIQUE");
elem.value = randomNum;

      



  • Your element has no ID ID_UNIQUE

  • You can run this code before the form is loaded

The simplest solution is to do the following, making sure you call this after the HTML is loaded:

   <input type="hidden" name="ID_UNIQUE" id="ID_UNIQUE" />
   <script>
      var now = new Date();
      var randomNum = '';
      randomNum += Math.round(Math.random()*9);
      randomNum += Math.round(Math.random()*9);
      randomNum += now.getTime();
      var elem = document.getElementById("ID_UNIQUE").value = randomNum;
    </script>
}

      

+6


source







All Articles