Search code examples
javascripthidden-field

Javascript Random Number Generator to Hidden Field


I have a script that creates 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 the "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 it doesn't work. When the form is submitted the value is blank. Thoughts?

Any help is greatly appreciated


Solution

  • There's no onsubmit for input fields, therefore this.ID_UNIQUE.value=randomNum is never running.

    Also, regarding the following code

    var elem = document.getElementById("ID_UNIQUE");
    elem.value = randomNum;
    
    • Your element doesn't have an ID of ID_UNIQUE
    • You may be running that code before the form is loaded

    The simplest solution is to do the following, making sure you do call this after your 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>
    }