Hi everyone I'm trying to manually assign a value to an html date input field. But it doesn't work.
First I tried to pass the value the way I do it for ordinary input box
<?php $newDate2 = '03/31/2014'; ?>
<form name='RegForm' method='GET'>
<input type="date" name="sdate" id="sdate" value="<?php echo $newDate2; ?>" required>
</form>
When It didn't work I tried to Use Javascript width something like this:
<head>
<script type="text/javascript">
function showInvoiceDate(){
var mYDate = new Date('2011-04-11');
alert(mYDate);
document.getElementById("sdate").value=mYDate;
}
</script>
</head>
<body onload="showInvoiceDate();">
<form name='RegForm' method='GET'>
<input type="date" name="sdate" id="sdate" required>
</form>
</body>
The function is being prompted. Because Alert box shows the value of myDate
But the value of date box is not being changet its still mm/dd/yyy
So What am I doing wrong?
The date should be in the format YYYY-MM-DD
. Single digit days and months should be padded with a 0. January is 01.
From the documentation:
A string representing a date. Value: A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0.
PHP - code should be:
<?php $newDate2 = "2014-03-31"; ?>
<form name='RegForm' method='GET'>
<input type="date" name="sdate" id="sdate" value="<?= $newDate2; ?>" required>
</form>
Tested and it works for me.
Javascript - you need to construct the date string, then set it, like:
var dateString = mYDate.getUTCFullYear() + "-" + (mYDate.getUTCMonth()+1) + "-" + mYDate.getUTCDate();
document.getElementById("sdate").value = dateString ;
I didn't test the JS version, but it should work.