Using javascript, how can we auto insert the current DATE and TIME into a form input field.
I'm building a "Problems" form to keep track of user submitted complaints about a certain service. I'm collecting as much info as possible. I want to save the staff here from having to manually enter the date and time each time they open the form.
I have this snippet of code:
<input id="date" name="date" value="javascript:document.write(Date()+'.')"/>
but it's not working.
many thanks for any help.
<input type="datetime-local"> <input> elements of type datetime-local create input controls that let the user easily enter both a date and a time, including the year, month, and day as well as the time in hours and minutes.
On the Design tab, in the Header / Footer group, click Date and Time. The Date and Time dialog box appears. Clear the Include Date check box if you do not want to include the date. If you want to include the date, click the date format that you want to use.
You need to add a script that calls getDate() from js.
It sounds like you are going to be storing the value that input field contains after the form is submitted, which means you are using a scripting language. I would use it instead of JavaScript as most scripting languages have better time/date formatting options. In PHP you could do something like this:
<input id="date" name="date" value="<?php echo date("M j, Y - g:i"); ?>"/>
Which would fill the field with "Jun 16, 2009 - 8:58"
Javascript won't execute within a value attribute. You could do something like this, though:
<input id="date" name="date">
<script type="text/javascript">
document.getElementById('date').value = Date();
</script>
You'd probably want to format the date as you prefer, because the default output of Date() looks something like: Tue Jun 16 2009 10:47:10 GMT-0400 (Eastern Daylight Time)
. See this SO question for info about formatting a date.
<input type="date" id="myDate" />
<script type="text/javascript">
function SetDate()
{
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById('myDate').value = today;
}
</script>
<body onload="SetDate();">
found here: http://jsbin.com/oqekar/1/edit?html,js,output
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With