user2066907
user2066907

Reputation: 45

Submit today's date as a hidden form input value

I need to send the current date in this format yyyymmdd via a hidden form input field.

I have the date formatted as I want with this javascript

function getDate()
{
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = yyyy+mm+dd;
}

And this is my form input field

<input type="hidden" name="startdate" onload="this.value = getDate();"/>

I've tried several ways to assign the date above to my var startdate and send it to the server, without any success.

Can you show me how to pass the date to my hidden input field when the page loads?

And I'm wondering if this posses any problems with regards to security and hackers?

Thanks for your help

Upvotes: 3

Views: 18699

Answers (2)

PSR
PSR

Reputation: 40338

<input type="hidden" name="startdate" id="todayDate"/>
<script type="text/javascript">
function getDate()
{
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm}
    today = yyyy+""+mm+""+dd;

    document.getElementById("todayDate").value = today;
}

//call getDate() when loading the page
getDate();
</script>

Upvotes: 3

Luke
Luke

Reputation: 102

If you are using the date for some kind of validation then for security you would be much better off using server side scripting; that way the client can't spoof dates.

Furthermore, you shouldn't use an <input>, even if you used the server side to generate the date, because you could still spoof the time using Firebug or many other web developer tools. The HTTP POST (or whatever) submitted could contain spoofed data. In the end nothing is 100% secure though.

Upvotes: 4

Related Questions