0

Hey guys my onClick Event doesn't put the date into the text input field.

<input class="span2" id="datum" name="datum" type="date">
<button class="btn" type="button" onclick="datum()">Heute</button>

<script type="text/javascript">
function datum() {
    var datum = new Date();
    var tag = datum.getDate();
    var monat = datum.getMonth();
    var jahr = datum.getFullYear();
    var element = document.getElementById("datum");
    element.innerHTML = tag + "." + monat + "." + jahr;
}
</script>
Siguza
  • 21,155
  • 6
  • 52
  • 89
Nils Blaumer
  • 19
  • 1
  • 6

2 Answers2

1
  1. Use .value instead of .innerHTML.
  2. Try not to use the same name, id and function name
  3. Add one to the month. JS months are 0-based.
  4. Pad with leading 0 for a proper date
  5. change type=date to type=text since you want to use a different format

    Is there any way to change input type="date" format? The HTML5 date input specification [1] refers to the RFC3339 specification, which specifies a full-date format equal to: yyyy-mm-dd.

Like this

element.value = tag + "." + (monat+1) + "." + jahr;

function pad(num) {
  return String("0" + num).slice(-2);
}
function heute() {
    var datum = new Date();
    var tag = datum.getDate();
    var monat = datum.getMonth();
    var jahr = datum.getFullYear();
    var element = document.getElementById("datum");
    element.value = pad(tag) + "." + pad(monat+1) + "." + jahr;
}
<input class="span2" id="datum" name="datum" type="text" placeholder="tt.mm.jjjj">
<button class="btn" type="button" onclick="heute()">Heute</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • It does in my snippet above – mplungjan Apr 28 '15 at 16:58
  • i copied your code but it doesnt work, i think it is something with the javascript snippet... – Nils Blaumer Apr 28 '15 at 17:01
  • There must be something in your page - or your browser does not like the same name, ID and function name - I changed the function name to heute – mplungjan Apr 28 '15 at 21:36
  • @NilsBlaumer thanks for accepting. If your "it does not work" comment is no longer relevant, please delete the comment so other visitors do not think the code fails – mplungjan Aug 22 '18 at 08:02
0
<input class="span2" id="datum" name="datum" type="text" value="<?php echo date("d.m.Y"); ?>" required>
<button class="btn" type="button">Heute</button>

I did it with PHP :P

Nils Blaumer
  • 19
  • 1
  • 6