Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto insert date and time in form input field?

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.

like image 252
Mo Boho Avatar asked Jun 16 '09 14:06

Mo Boho


People also ask

How do you insert date and time in HTML?

<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.

How do I add a date to a form?

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.

How do I display current date and time in HTML textbox?

You need to add a script that calls getDate() from js.


3 Answers

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"

like image 139
Scott Avatar answered Oct 10 '22 04:10

Scott


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.

like image 42
Daniel Vandersluis Avatar answered Oct 10 '22 03:10

Daniel Vandersluis


<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

like image 32
Usman Avatar answered Oct 10 '22 03:10

Usman