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>
4
  • 3
    use .value instead of innerHTML. Also add one to the month. JS months are 0 based Commented Apr 28, 2015 at 16:47
  • how do you mean that i need to add one to the month? Commented Apr 28, 2015 at 16:49
  • Also, you'll need to format the date string as required by the input (i.e. yyyy-mm-dd). Commented Apr 28, 2015 at 16:54
  • how can i make this? Commented Apr 28, 2015 at 16:58

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

It does in my snippet above
i copied your code but it doesnt work, i think it is something with the javascript snippet...
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
@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
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

1 Comment

That just sets the date, then you can drop the button.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.