Bob Balm
Bob Balm

Reputation: 11

Saving gettime to form field

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?

Upvotes: 1

Views: 146

Answers (1)

John Hudson
John Hudson

Reputation: 17

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.

Upvotes: 1

Related Questions