Search code examples
javascriptdateformsunix-timestampauto-populate

Pre-populate Form Field With The Internal Millisecond Clock From Javascript


I have a form on my website that I need to pre-populate with the current unix millisecond timestamp.

I do have another form field (in the same form) which successfully pre-populates the Date (Month, Day, Year) with the following code:

 <div>DATE<br><input name="date" id="date"></div>

 <script>
 (function() {
 var days = ['','','','','','',''];
 var months =
['Jan','Feb','Mar','Apr','May','June','July','Aug','Sept','Oct','Nov','Dec'];
Date.prototype.getMonthName = function() {
return months[ this.getMonth() ]; };
Date.prototype.getDayName = function() {
return days[ this.getDay() ]; }; })();
var now = new Date();
var day = now.getDayName();
var month = now.getMonthName();
document.getElementById('date').value = day + ' ' + month + ' ' + 
now.getDate() + ', ' + now.getFullYear();
</script>

However... I'm not having the same luck when attempting to pre-populate a second form field with the Unix Millisecond timestamp using this code:

 <div>TIMESTAMP URL<br><input name="timeStampURL" id="timeStampURL"></div>

 <script>
 var d = new Date();
 document.getElementById('timeStampURL').innerHTML = d.getTime();
 </script>

I don't understand why the two codes behave differently that way, but any advice as to how to get that script to pre-populate the field would be appreciated.


Solution

  • Input elements don't have any content, so setting their innerHTML property does nothing. Your first function is setting the value attribute, so should your second:

    function showTimeValue() {
      document.getElementById('timeValue').value = Date.now();
    }
    
    window.onload = showTimeValue;
    <input id="timeValue">
    <button onclick="showTimeValue()">Update time value</button>

    Each time you run the code, you'll get an updated value.