1

I'm a relative JS newbie, but I'm in a bit of a pickle - for a form submission system, I need to populate a form field with a unique ID (can be anything, as long as it's relatively certain to be unique).

I thought of using getTime(), since that produces a sufficiently long and unique number for my requirements. But I can't seem to wrap my head around the code required to populate a regular (hidden) text field with this value, despite several topics on SO asking similar questions.

The form and all the HTML is already in place, all I need is the js script. Can anyone help me out?

Bob Balm
  • 11
  • 2
  • 1
    Could you provide any code you've written so far? – NTL Jun 03 '16 at 17:34
  • Try [this](http://stackoverflow.com/a/8012120/456135) – Anupam Jun 03 '16 at 17:38
  • I'm at home now but from memory, it was something like: `var d = new Date(); var n = d.getTime(); document.getElementsbyName("MyFormField").value = n;` And then the form input would have a name of MyFormField. – Bob Balm Jun 03 '16 at 19:19

1 Answers1

1
var timestamp = new Date().getUTCMilliseconds();


var now = new Date(); 
timestamp =now.getFullYear().toString(); 
// 2011
timestamp += (now.getFullMonth < 9 ? '0' : '') + now.getFullMonth().toString();
 // JS months are 0-based, so +1 and pad with 0's
 timestamp += (now.getDate < 10) ? '0' : '') + now.getDate().toString(); 

then to append that timestamp to your input

<input name="timestamp" id="input" type="hidden"/>

then:

document.querySelector('#input').value = timestamp;

Edit: Final Code

<script>
     document.onreadystatechange = function()
     {
          if(document.readyState == "interactive")
          {
                     var now = new Date(); 
timestamp =now.getFullYear().toString(); 
// 2011
timestamp += (now.getFullMonth < 9 ? '0' : '') + now.getFullMonth().toString();
 // JS months are 0-based, so +1 and pad with 0's
 timestamp += (now.getDate < 10) ? '0' : '') + now.getDate().toString(); 

               document.querySelector('#input').value = timestamp;
          }
     }
</script>

Put this script tag at the bottom of the document.