0

I have a problem with HTML and I can't find reliable help anywhere. I have an HTML form with some fields and I want to insert current date and time into two form fields. I used the example from: Auto insert date and time in form input field? and inserted such a JS code (by the way, this snippet also comes from one of StackOverflow questions):

<script type="text/javascript">
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var hh = today.getHours();
var mn = today.getMinutes();
if(dd<10) {
    dd='0'+dd
} 

if(mm<10) {
    mm='0'+mm
} 
if(hh<10) {
    hh='0'+hh
}
if(mn<10) {
    mn='0'+mn
}
today = yyyy+'-'+mm+'-'+dd;
var now = hh+':'+mn;
document.write(today);
document.write(now);
</script>

This HTML code is supposed to insert date and time into form fields:

<p>Data: 
<input type="text" name="date" id="iddate" size="10" />
<script type="text/javascript">
document.getElementById('iddate').value = document.write(today);
</script>
</p>
<p>Godzina: <input type="text" name="time" id="idtime" size="5" />
<script type="text/javascript">
document.getElementById('idtime').value = document.write(now);
</script>
</p>

but the result is as you can see here: date and time appear next to the fields and the value of fields is "undefined". I don't understand what's going on. Can you give me some advice? At the top of the site are the results of document.write() functions and they look correct.

Community
  • 1
  • 1
user3855877
  • 99
  • 1
  • 1
  • 11

2 Answers2

0

Just remove 'document.write'.

call your code like this:

 document.getElementById('iddate').value = today;

and like this:

 document.getElementById('idtime').value = now;

document.write() appends the document with the specified text and returns undefined, so setting something to that value, just makes it 'undefined'

0

when you are trying to assign some value to some field in javascript you simply do:

document.getElementById('yourId').value = value_to_assign;

And do not use document.write because The document.write methods outputs a string directly into page.

read facts about document.write :http://javascript.info/tutorial/document-write

Suchit kumar
  • 11,809
  • 3
  • 22
  • 44