Nils Blaumer
Nils Blaumer

Reputation: 19

Javascript onclick put text into an text field

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>

Upvotes: 0

Views: 1942

Answers (2)

mplungjan
mplungjan

Reputation: 178285

  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>

Upvotes: 1

Nils Blaumer
Nils Blaumer

Reputation: 19

<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

Upvotes: 0

Related Questions