views:

1274

answers:

9

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.

+1  A: 

The fastest way to get date formatting thats any good is to use datejs.

The lib is really easy to use and does give you very pretty formatting.


as far as your code snippet, dont use document.write if you can help it. try

 document.getElementById("date").value = new Date().toUTCString();
mkoryak
+1  A: 

Perhaps try the below. Uses JQuery, which is much cleaner in structure.

Good supporting thread.

Paul
+2  A: 

See the example, http://jsbin.com/ahehe

Use the JavaScript date formatting utility described here.

<input id="date" name="date" />

<script>
   document.getElementById('date').value = (new Date()).format("m/dd/yy");
</script>
altCognito
+7  A: 

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.

Daniel Vandersluis
A: 
<input id="date" name="date" />
<script type="text/javascript">
document.getElementById("date").value = new Date();
</script>
jiggy
+1  A: 

It's not an answer to your question, but I strongly recommend not to rely on the users input, patience and having JavaScript activated. I therefore would suggest a server side approach to handle all the timestamps. Additionally it might cause problems for your stuff, if the user is mailing you from the future (different time zone).

merkuro
A: 

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"

Scotty
A: 

Brilliant! Just what I was after as well, so thankyou Scotty!

A: 

other choice

document.getElementById("my_date:box").value = ( Stamp.getDate()+"/"+(Stamp.getMonth() + 1)+"/"+(Stamp.getYear()) );
aguz